☰
Humanizer LetterCasing 枚举完全指南:四档字符串大小写策略与底层实现解析
2026/9/29 9:15:45 网站建设 项目流程
  • 开发工具

【免费下载链接】Humanizer

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities

项目地址:https://gitcode.com/gh_mirrors/hu/Humanizer
点击查看免费下载

Humanizer 中的LetterCasing枚举定义了字符串输出所需的四种大小写风格(Title、AllCaps、LowerCase、Sentence),是ApplyCase、字符串Humanize、枚举Humanize等核心 API 的公共开关。本文以 Humanizer.LetterCasing API 文档 为骨架,结合源码与测试,完整讲解每个枚举成员的确切行为、调用方式、底层 Transformer 机制与常见注意事项,读完即可在 .NET 项目中精确控制任何字符串、枚举名称的显示大小写。

LetterCasing 枚举:四个成员与官方语义

LetterCasing位于Humanizer命名空间,是驱动字符串大小写转换的标准枚举。其官方定义见 LetterCasing.cs,原文注释明确说明其用途为 "Options for specifying the desired letter casing for the output string"(为输出字符串指定期望的大小写风格)。

成员枚举值官方示例语义
Title0SomeString -> Some String标题大小写:每个单词首字母大写
AllCaps1SomeString -> SOME STRING全大写
LowerCase2SomeString -> some string全小写
Sentence3SomeString -> Some string句子大小写:仅首字符大写,其余保持原样

四个成员覆盖了开发中最常见的四种文本展示需求:标题/栏目名(Title)、强调或告警(AllCaps)、统一小写存储与匹配(LowerCase)、自然语句(Sentence)。

核心入口一:ApplyCase扩展方法

LetterCasing最直接的消费方是 CasingExtensions.cs 中的ApplyCase扩展方法,它把枚举值映射到对应的字符串变换器:

public static string ApplyCase(this string input, LetterCasing casing) => casing switch { LetterCasing.Title => input.Transform(To.TitleCase), LetterCasing.LowerCase => input.Transform(To.LowerCase), LetterCasing.AllCaps => input.Transform(To.UpperCase), LetterCasing.Sentence => input.Transform(To.SentenceCase), _ => throw new ArgumentOutOfRangeException(nameof(casing)) };

行为示例(取自源码 XML 注释)

"some string".ApplyCase(LetterCasing.Title) // => "Some String" "SOME STRING".ApplyCase(LetterCasing.LowerCase) // => "some string" "some string".ApplyCase(LetterCasing.AllCaps) // => "SOME STRING" "some string".ApplyCase(LetterCasing.Sentence) // => "Some string"

关于非法值的异常处理

注意switch表达式的兜底分支:传入不在 0~3 范围内的值会抛出ArgumentOutOfRangeException。这一点在 EnumHumanizeTests.cs 中有对应验证:Assert.Throws<ArgumentOutOfRangeException>(() => value.Humanize((LetterCasing)42))。

核心入口二:字符串Humanize(LetterCasing)组合

LetterCasing最常见的实际用途是与Humanize配合,把 PascalCase / 下划线 / 连字符文本先拆分再套用大小写。实现在 StringHumanizeExtensions.cs:

public static string Humanize(this string input, LetterCasing casing) => input .Humanize() .ApplyCase(casing);

即先执行无参数的Humanize()(拆分单词、处理首字母缩写与下划线/连字符),再套用指定大小写。官方注释示例:

"PascalCaseInputString".Humanize(LetterCasing.AllCaps) // => "PASCAL CASE INPUT STRING" "PascalCaseInputString".Humanize(LetterCasing.LowerCase) // => "pascal case input string" "PascalCaseInputString".Humanize(LetterCasing.Title) // => "Pascal Case Input String"

测试用例 StringHumanizeTests.cs 也验证了组合行为的细节,例如土耳其语文化下的标题转换:

[Theory, UseCulture("tr-TR")] [InlineData("istanbulInputString", "İstanbul Input String")] public void CanHumanizeStringIntoTitleCaseInTurkish(...)

这条测试同时印证了LetterCasing.Title会尊重tr-TR这类需要特殊大小写规则的文化。

核心入口三:枚举Humanize(LetterCasing)

LetterCasing也可作为枚举人性化输出的参数,定义在 EnumHumanizeExtensions.cs:

public static string Humanize<[DynamicallyAccessedMembers(...)] T>(this T input, LetterCasing casing) where T : struct, Enum => Humanize(input, casing, EnumHumanizeSource.Default);

官方示例:

enum UserType { AnonymousUser, RegisteredUser } UserType.AnonymousUser.Humanize(LetterCasing.AllCaps) // => "ANONYMOUS USER" UserType.AnonymousUser.Humanize(LetterCasing.Title) // => "Anonymous User" UserType.AnonymousUser.Humanize(LetterCasing.LowerCase) // => "anonymous user"

测试还表明:当枚举成员带有DescriptionAttribute或DisplayAttribute时,四种LetterCasing都不会改写属性中的既定文本(见 EnumHumanizeTests.cs 中CasingPreservesDescriptionAttribute/CasingPreservesDisplayAttribute两个 Theory),这与“属性文本优先、否则按成员名拆分”的设计一致。

除上述入口外,InflectorExtensions的标题化方法内部也复用了ApplyCase(LetterCasing.Title)(见 InflectorExtensions.cs),可见该枚举是整个大小写体系的公共基础。

底层原理:Transformer 机制

ApplyCase最终把工作委托给To门户(To.cs)上的四个ICulturedStringTransformer单例:To.TitleCase、To.LowerCase、To.UpperCase、To.SentenceCase。它们支持两个重载:无文化参数时使用CultureInfo.CurrentCulture,也可显式传入CultureInfo进行文化敏感转换:

public static string Transform(this string input, CultureInfo culture, params ICulturedStringTransformer[] transformers)

因此LetterCasing的大小写行为在根本上是由当前线程文化(或显式传入文化)的TextInfo驱动的。

Title 大小写的精妙细节

ToTitleCase.cs 是四个变换器中最复杂的,值得单独展开:

  • 双路径设计:纯 ASCII 输入走高性能的TryTransformAscii快速路径(逐字符扫描、按需复制到char[]缓冲),一旦遇到非 ASCII 字符则回退到正则路径TransformWithRegex,正则模式为(\w|[^\u0000-\u007F])+'?\w*(兼容撇号收缩词,如don't)。在 .NET 7+ 上该正则使用[GeneratedRegex]生成。
  • 全大写单词保留原样:AllAsciiCapitals/AllCapitals判断使HTML、USA这类单词不会被错误改写,与测试中"HTML" -> "HTML"的断言一致。
  • 冠词/连词/介词小写化:位于非句首的a, an, as, at, by, if, in, of, on, or, so, to, up, and, but, for, nor, off, the, via, yet保持小写,这是标题大小写的经典排版规则(见IsArticleOrConjunctionOrPreposition方法)。测试 CasingTests.cs 中"title case (with parenthesis)" -> "Title Case (With Parenthesis)"也验证了括号内单词同样参与处理。
  • 文化敏感 ASCII 大写:当文化为tr(土耳其语)或az(阿塞拜疆语)前缀时,UsesCultureSensitiveAsciiCasing返回true,大小写转换改走TextInfo.ToUpper/ToLower,从而正确处理土耳其语点号问题(如istanbul在 tr-TR 下转为İstanbul)。

Sentence 大小写的极简语义

ToSentenceCase.cs 实现非常克制:仅当输入非空且首字符不是大写时,用TextInfo.ToUpper大写首字符,其余字符一律不动。这与 .NET 自带的ToTitleCase(会强制小写其余字符)不同,也是Sentence与Title的核心区别。测试中的三组断言清楚展示了这一行为:

"lower case statement".ApplyCase(LetterCasing.Sentence) // "Lower case statement" "Sentence casing".ApplyCase(LetterCasing.Sentence) // "Sentence casing"(首字符已大写,原样返回) "honors UPPER case".ApplyCase(LetterCasing.Sentence) // "Honors UPPER case"(其余字符不被小写化)

测试验证一览

仓库测试为四种大小写策略提供了完整的行为契约:

  • CasingTests.cs:ApplyCase四个成员各自的 Theory 断言,覆盖标题保留大写、句子仅改首字符、全大/小写等边界。
  • StringHumanizeTests.cs:Humanize(LetterCasing)组合行为,含 tr-TR 文化的标题转换与阿拉伯语 Unicode 保留。
  • EnumHumanizeTests.cs:枚举 +LetterCasing的四档行为、Description/Display 属性保留、非法值异常。

使用建议与注意事项

  1. 区分Title与Sentence:需要整句标题排版用Title;只需句首大写、保留句中既有大小写(如专有名词)时用Sentence。
  2. 文化一致性:LetterCasing的所有转换默认受CultureInfo.CurrentCulture影响,涉及土耳其语等特殊大小写规则时应确保运行环境文化正确,或显式传入文化。
  3. 枚举属性优先:对带Description/Display特性的枚举成员,Humanize(LetterCasing)不会改写属性文本,请勿期望通过 casing 参数改变这类既定输出。
  4. 非法值防护:库会对越界枚举值抛出ArgumentOutOfRangeException,调用方应只传Title、AllCaps、LowerCase、Sentence四者之一。
  5. 性能:纯 ASCII 输入在Title下走免正则的快速路径,批量处理标识符类文本时天然高效;含非 ASCII 字符时自动回退正则路径,无需调用方干预。

将LetterCasing与ApplyCase、Humanize组合使用,即可在展示层、日志层、报表标题等场景下以统一、可测试的方式完成全部大小写需求,这正是 Humanizer 围绕该枚举建立的完整能力闭环。

  • 开发工具

【免费下载链接】Humanizer

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities

项目地址:https://gitcode.com/gh_mirrors/hu/Humanizer
点击查看免费下载
上一篇:nosurf完全指南:如何用Go语言打造安全无虞的CSRF防护中间件
下一篇:Laravel Installer 教程

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询