人物Humanizer满足您的所有.NET需要操纵和显示字符串,枚举,日期,时间,时间,数字和数量的需求。
您可以将人类器作为nuget软件包安装:
仅英语: Humanizer.Core
所有语言: Humanizer
支持以下框架:Net4.8,Net6,Net7和Net8
注意:Nuget还针对NetStandard2。这是为了启用需要NetStandard2的情况。例如Roslyn分析仪或MSBUILD任务。不支持其他可以消费NetStandard2(示例Net4.6.1到Net 4.7.2)的其他框架(上面列出的)。例如,不支持Net4.6.1至Net4.7.2。
另外,人体器符号是用Sourcelink索引的,并包含在软件包中,因此您可以在调试代码时逐步浏览人体器代码。
您可以根据安装的Nuget软件包选择哪些软件包。默认情况下,主要的Humanizer 2.0软件包安装了所有支持的语言,就像1.x中一样。如果不确定,请使用主要的Humanizer套件。
这是选项:
Humanizer套件。这会吸引Humanizer.Core和所有语言软件包。Humanizer.Core软件包。只有英语资源可用Humanizer.Core.fr 。您可以通过安装多种语言包含多种语言。此处的评论中有关其工作方式的详细说明。
Humanize琴弦扩展使您可以将原本计算机化的字符串变成更可读的人类友好型字符串。其基础是在BDDFY框架中设定的,其中类名称,方法名称和属性变成了人类可读句子。
"PascalCaseInputStringIsTurnedIntoSentence" . Humanize ( ) => "Pascal case input string is turned into sentence"
"Underscored_input_string_is_turned_into_sentence" . Humanize ( ) => "Underscored input string is turned into sentence"
"Underscored_input_String_is_turned_INTO_sentence" . Humanize ( ) => "Underscored input String is turned INTO sentence"请注意,仅包含上部案例字母的字符串,仅由一个单词组成,总是将其视为首字母缩写词(无论其长度如何)。为确保任何任意字符串将始终被人性化,您必须使用转换(请参见下面的Transform方法):
// acronyms are left intact
"HTML" . Humanize ( ) => "HTML "
// any unbroken upper case string is treated as an acronym
" HUMANIZER" . Humanize ( ) => "HUMANIZER"
"HUMANIZER" . Transform ( To . LowerCase , To . TitleCase ) => "Humanizer"您还可以指定所需的信件套管:
"CanReturnTitleCase" . Humanize ( LetterCasing . Title ) => "Can Return Title Case "
" Can_return_title_Case" . Humanize ( LetterCasing . Title ) => "Can Return Title Case"
"CanReturnLowerCase" . Humanize ( LetterCasing . LowerCase ) => "can return lower case"
"CanHumanizeIntoUpperCase" . Humanize ( LetterCasing . AllCaps ) => "CAN HUMANIZE INTO UPPER CASE"
LetterCasingAPI及其接受它的方法是v0.2时代的遗产,将来将被弃用。您可以使用下面说明的Transform方法,而不是这些。
就像您可以将计算机友好的人类化成人类友好的字符串一样,您可以将人类友好的字符串变成计算机友好的字符串:
"Pascal case input string is turned into sentence" . Dehumanize ( ) => "PascalCaseInputStringIsTurnedIntoSentence"有一种Transform方法可以取代接受LetterCasing LetterCasing , ApplyCase和Humanize过载。变换方法签名如下:
string Transform ( this string input , params IStringTransformer [ ] transformers )而且有一些IStringTransformer的实施方式用于字母外壳:
"Sentence casing" . Transform ( To . LowerCase ) => "sentence casing "
" Sentence casing ".Transform(To.SentenceCase) => " Sentence casing "
"Sentence casing" . Transform ( To . TitleCase ) => "Sentence Casing"
"Sentence casing" . Transform ( To . UpperCase ) => "SENTENCE CASING" LowerCase是一个公共静态属性,它返回了实现IStringTransformer的专用ToLowerCase类的实例To并且知道如何将字符串变成较低的情况。
使用Transform和IStringTransformer而不是ApplyCase LetterCasing好处是, LetterCasing是一个枚举,您只能使用框架中的内容,而IStringTransformer是一个接口,您可以在代码库中实现一次,并将其用于Transform方法,允许允许易于扩展。
您可以使用Truncate方法截断string :
"Long text to truncate" . Truncate ( 10 ) => "Long text…"默认情况下, '…'字符用于截断字符串。使用'…'字符而不是"..."的优点是,前者只采用一个字符,因此允许在截断之前显示更多文本。如果需要,也可以提供自己的截断字符串:
"Long text to truncate" . Truncate ( 10 , "---" ) => "Long te -- - "默认的截断策略Truncator.FixedLength是将输入字符串截断为特定的长度,包括截断字符串长度。还有另外两个可用的截断策略:一个用于固定数量的(alpha-numerical)字符,一个用于固定数量的单词。要在截断时使用特定的截断器,上一个示例中显示的两个Truncate方法都具有超载,使您可以指定用于截断的ITruncator实例。以下是如何使用三个提供的截断器的示例:
"Long text to truncate" . Truncate ( 10 , Truncator . FixedLength ) => "Long text…"
"Long text to truncate" . Truncate ( 10 , "---" , Truncator . FixedLength ) => "Long te---"
"Long text to truncate" . Truncate ( 6 , Truncator . FixedNumberOfCharacters ) => "Long t…"
"Long text to truncate" . Truncate ( 6 , "---" , Truncator . FixedNumberOfCharacters ) => "Lon---"
"Long text to truncate" . Truncate ( 2 , Truncator . FixedNumberOfWords ) => "Long text…"
"Long text to truncate" . Truncate ( 2 , "---" , Truncator . FixedNumberOfWords ) => "Long text---"请注意,您还可以通过实现ITruncator接口来使用创建自己的截断器。
还有一个选项可以选择是从开始( TruncateFrom.Left )还是末端( TruncateFrom.Right )截断字符串。默认值是上面示例所示的正确的。下面的示例显示了如何从字符串的开头截断:
"Long text to truncate" . Truncate ( 10 , Truncator . FixedLength , TruncateFrom . Left ) => "… truncate"
"Long text to truncate" . Truncate ( 10 , "---" , Truncator . FixedLength , TruncateFrom . Left ) => "---runcate"
"Long text to truncate" . Truncate ( 10 , Truncator . FixedNumberOfCharacters , TruncateFrom . Left ) => "…o truncate"
"Long text to truncate" . Truncate ( 16 , "---" , Truncator . FixedNumberOfCharacters , TruncateFrom . Left ) => "---ext to truncate"
"Long text to truncate" . Truncate ( 2 , Truncator . FixedNumberOfWords , TruncateFrom . Left ) => "…to truncate"
"Long text to truncate" . Truncate ( 2 , "---" , Truncator . FixedNumberOfWords , TruncateFrom . Left ) => "---to truncate"直接在枚举成员身上调用ToString通常会导致用户的理想输出少。解决方案通常是使用DescriptionAttribute数据注释,然后在运行时阅读以获取更友好的输出。那是一个很好的解决方案;但是,通常我们只需要在枚举成员的单词之间放置一些空间 - 这就是String.Humanize()做得很好。对于枚举:
public enum EnumUnderTest
{
[ Description ( "Custom description" ) ]
MemberWithDescriptionAttribute ,
MemberWithoutDescriptionAttribute ,
ALLCAPITALS
}您会得到:
// DescriptionAttribute is honored
EnumUnderTest . MemberWithDescriptionAttribute . Humanize ( ) => "Custom description"
// In the absence of Description attribute string.Humanizer kicks in
EnumUnderTest . MemberWithoutDescriptionAttribute . Humanize ( ) => "Member without description attribute"
// Of course you can still apply letter casing
EnumUnderTest . MemberWithoutDescriptionAttribute . Humanize ( ) . Transform ( To . TitleCase ) => "Member Without Description Attribute"您不仅限于用于自定义说明的DescriptionAttribute 。具有string Description属性计数的枚举成员应用于枚举成员的任何属性。这是为了帮助解决缺少DescriptionAttribute平台,并且还允许DescriptionAttribute的子类。
您甚至可以配置Attibute属性的名称,以用作描述。
Configurator.EnumDescriptionPropertyLocator = p => p.Name == "Info"
如果您需要提供本地描述,则可以使用DisplayAttribute数据注释。
public enum EnumUnderTest
{
[ Display ( Description = "EnumUnderTest_Member" , ResourceType = typeof ( Project . Resources ) ) ]
Member
}您会得到:
EnumUnderTest . Member . Humanize ( ) => "content" // from Project.Resources found under "EnumUnderTest_Member" resource key希望这将有助于避免具有不必要属性的垃圾货物!
将一根绳子伸入最初是人性化的枚举中! API看起来像:
public static TTargetEnum DehumanizeTo < TTargetEnum > ( this string input )用法是:
"Member without description attribute" . DehumanizeTo < EnumUnderTest > ( ) => EnumUnderTest . MemberWithoutDescriptionAttribute就像人性化API一样,它也尊重Description属性。您不必提供人性化过程中提供的壳体:它可以解决。
对于原始枚举在编译时不知道的何时,还有一个非传播的对应物:
public static Enum DehumanizeTo ( this string input , Type targetEnum , NoMatch onNoMatch = NoMatch . ThrowsException )可以像以下方式使用:
"Member without description attribute" . DehumanizeTo ( typeof ( EnumUnderTest ) ) => EnumUnderTest . MemberWithoutDescriptionAttribute默认情况下,这两种方法都无法与目标枚举相匹配提供的输入时,都会NoMatchFoundException 。在非生成方法中,您还可以要求通过将第二个可选参数设置为NoMatch.ReturnsNull来返回null的方法。
您可以使DateTime或DateTimeOffset的实例Humanize ,并取回一个字符串,告诉时间是:
DateTime . UtcNow . AddHours ( - 30 ) . Humanize ( ) => "yesterday"
DateTime . UtcNow . AddHours ( - 2 ) . Humanize ( ) => "2 hours ago"
DateTime . UtcNow . AddHours ( 30 ) . Humanize ( ) => "tomorrow"
DateTime . UtcNow . AddHours ( 2 ) . Humanize ( ) => "2 hours from now"
DateTimeOffset . UtcNow . AddHours ( 1 ) . Humanize ( ) => "an hour from now" Humanizer支持本地和UTC日期以及偏移( DateTimeOffset )的日期。您还可以提供要比较输入日期的日期。如果null,它将使用当前日期作为比较基础。而且,可以明确指定要使用的文化。如果不是,则使用当前线程的当前UI文化。这是API签名:
public static string Humanize ( this DateTime input , bool utcDate = true , DateTime ? dateToCompareAgainst = null , CultureInfo culture = null )
public static string Humanize ( this DateTimeOffset input , DateTimeOffset ? dateToCompareAgainst = null , CultureInfo culture = null )此方法可用于许多本地化。这里有几个例子:
// In ar culture
DateTime . UtcNow . AddDays ( - 1 ) . Humanize ( ) => "أمس"
DateTime . UtcNow . AddDays ( - 2 ) . Humanize ( ) => "منذ يومين"
DateTime . UtcNow . AddDays ( - 3 ) . Humanize ( ) => "منذ 3 أيام"
DateTime . UtcNow . AddDays ( - 11 ) . Humanize ( ) => "منذ 11 يوم"
// In ru-RU culture
DateTime . UtcNow . AddMinutes ( - 1 ) . Humanize ( ) => "минуту назад"
DateTime . UtcNow . AddMinutes ( - 2 ) . Humanize ( ) => "2 минуты назад"
DateTime . UtcNow . AddMinutes ( - 10 ) . Humanize ( ) => "10 минут назад"
DateTime . UtcNow . AddMinutes ( - 21 ) . Humanize ( ) => "21 минуту назад"
DateTime . UtcNow . AddMinutes ( - 22 ) . Humanize ( ) => "22 минуты назад"
DateTime . UtcNow . AddMinutes ( - 40 ) . Humanize ( ) => "40 минут назад" DateTime.Humanize有两种策略。人性化:默认的策略如上所述,是基于精度的策略。要使用基于精确的策略,您需要对其进行配置:
Configurator . DateTimeHumanizeStrategy = new PrecisionDateTimeHumanizeStrategy ( precision : .75 ) ;
Configurator . DateTimeOffsetHumanizeStrategy = new PrecisionDateTimeOffsetHumanizeStrategy ( precision : .75 ) ; // configure when humanizing DateTimeOffset默认的精度设置为.75,但您也可以通过所需的精度。精度设置为0.75:
44 seconds => 44 seconds ago / from now
45 seconds => one minute ago / from now
104 seconds => one minute ago / from now
105 seconds => two minutes ago / from now
25 days => a month ago / from now Humanize的日期没有非人性化是一种有损的转变,人类友好的日期不是可逆的
您可以将Humanize在TimeSpan称为人性化的代表:
TimeSpan . FromMilliseconds ( 1 ) . Humanize ( ) => "1 millisecond"
TimeSpan . FromMilliseconds ( 2 ) . Humanize ( ) => "2 milliseconds"
TimeSpan . FromDays ( 1 ) . Humanize ( ) => "1 day"
TimeSpan . FromDays ( 16 ) . Humanize ( ) => "2 weeks"有一个可选的precision参数,适用于TimeSpan.Humanize ,它允许您指定返回值的精度。 precision的默认值为1,这意味着只有您在TimeSpan.FromDays(16).Humanize()中看到的最大时间单元才能返回。这是指定精度的一些示例:
TimeSpan . FromDays ( 1 ) . Humanize ( precision : 2 ) => "1 day" // no difference when there is only one unit in the provided TimeSpan
TimeSpan . FromDays ( 16 ) . Humanize ( 2 ) => "2 weeks, 2 days"
// the same TimeSpan value with different precision returns different results
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( ) => "2 weeks"
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 3 ) => "2 weeks, 1 day, 1 hour"
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 4 ) => "2 weeks, 1 day, 1 hour, 30 seconds"
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 5 ) => "2 weeks, 1 day, 1 hour, 30 seconds, 20 milliseconds"默认情况下,当使用precision参数时,空时间单元不计入返回值的精度。如果您不需要此行为,则可以使用countEmptyUnits参数使用过载的TimeSpan.Humanize 。领先的空时间单元永远不会计算。这是一个示例,显示了计数空单元的差异:
TimeSpan . FromMilliseconds ( 3603001 ) . Humanize ( 3 ) => "1 hour, 3 seconds, 1 millisecond"
TimeSpan . FromMilliseconds ( 3603001 ) . Humanize ( 3 , countEmptyUnits : true ) => "1 hour, 3 seconds"此方法可用于许多本地化:
// in de-DE culture
TimeSpan . FromDays ( 1 ) . Humanize ( ) => "Ein Tag"
TimeSpan . FromDays ( 2 ) . Humanize ( ) => "2 Tage"
// in sk-SK culture
TimeSpan . FromMilliseconds ( 1 ) . Humanize ( ) => "1 milisekunda"
TimeSpan . FromMilliseconds ( 2 ) . Humanize ( ) => "2 milisekundy"
TimeSpan . FromMilliseconds ( 5 ) . Humanize ( ) => "5 milisekúnd"可以明确指定要使用的文化。如果不是,则使用当前线程的当前UI文化。例子:
TimeSpan . FromDays ( 1 ) . Humanize ( culture : "ru-RU" ) => "один день"另外,可以指定最低时间单位,以避免滚动到较小的单位。例如:
TimeSpan . FromMilliseconds ( 122500 ) . Humanize ( minUnit : TimeUnit . Second ) => "2 minutes, 2 seconds" // instead of 2 minutes, 2 seconds, 500 milliseconds
TimeSpan . FromHours ( 25 ) . Humanize ( minUnit : TimeUnit . Day ) => "1 Day" //instead of 1 Day, 1 Hour此外,可以指定最大时间单位,以避免滚动到下一个最大的单元。例如:
TimeSpan . FromDays ( 7 ) . Humanize ( maxUnit : TimeUnit . Day ) => "7 days" // instead of 1 week
TimeSpan . FromMilliseconds ( 2000 ) . Humanize ( maxUnit : TimeUnit . Millisecond ) => "2000 milliseconds" // instead of 2 seconds默认的maxunit是TimeUnit.Week ,因为它给出了确切的结果。您可以将此价值增加到TimeUnit.Month或TimeUnit.Year它将根据每年365.2425天和每月30.436875天的近似值。因此,几个月的长度在30至31天之间交替,每四年为366天。
TimeSpan . FromDays ( 486 ) . Humanize ( maxUnit : TimeUnit . Year , precision : 7 ) => "1 year, 3 months, 29 days" // One day further is 1 year, 4 month
TimeSpan . FromDays ( 517 ) . Humanize ( maxUnit : TimeUnit . Year , precision : 7 ) => "1 year, 4 months, 30 days" // This month has 30 days and one day further is 1 year, 5 months当有多个时间单元时,它们会使用", "字符串:
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 3 ) => "2 weeks, 1 day, 1 hour"当TimeSpan为零时,默认行为将返回“ 0”,以及最小时间单元的任何内容。但是,如果您在呼叫Humanize时将true分配给toWords ,则该方法将返回“没有时间”。例如:
TimeSpan . Zero . Humanize ( 1 ) => "0 milliseconds"
TimeSpan . Zero . Humanize ( 1 , toWords : true ) => "no time"
TimeSpan . Zero . Humanize ( 1 , minUnit : Humanizer . Localisation . TimeUnit . Second ) => "0 seconds"使用collectionSeparator参数,您可以指定自己的分隔符字符串:
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 3 , collectionSeparator : " - " ) => "2 weeks - 1 day - 1 hour"还可以使用当前文化的收藏格式将时间单元组合在一起。为此,将null指定为collectionSeparator参数:
// in en-US culture
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 3 , collectionSeparator : null ) => "2 weeks, 1 day, and 1 hour"
// in de-DE culture
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 3 , collectionSeparator : null ) => "2 Wochen, Ein Tag und Eine Stunde"如果单词优先于数字, toWords: true参数”以将人源化时段中的数字转换为单词:
TimeSpan . FromMilliseconds ( 1299630020 ) . Humanize ( 3 , toWords : true ) => "two weeks, one day, one hour"通过称呼ToAge ,也可以将TimeSpan表示为年龄。对于未定义年龄表达的文化,结果将与呼叫Humanize相同(但默认的maxUnit等于TimeUnit.Year ) 。
// in en-US culture
TimeSpan . FromDays ( 750 ) . ToAge ( ) => "2 years old"
// in fr culture
TimeSpan . FromDays ( 750 ) . ToAge ( ) => "2 ans"您可以将任何IEnumerable称为Humanize ,以获取代表集合中对象的格式精美的字符串。默认情况下,将在每个项目上调用ToString()以获取其表示形式,但可以将格式化函数传递给Humanize 。此外,还提供了一个默认的分离器(英语中的“和”),但是可以将不同的分离器传递到Humanize中。
例如:
class SomeClass
{
public string SomeString ;
public int SomeInt ;
public override string ToString ( )
{
return "Specific String" ;
}
}
string FormatSomeClass ( SomeClass sc )
{
return string . Format ( "SomeObject #{0} - {1}" , sc . SomeInt , sc . SomeString ) ;
}
var collection = new List < SomeClass >
{
new SomeClass { SomeInt = 1 , SomeString = "One" } ,
new SomeClass { SomeInt = 2 , SomeString = "Two" } ,
new SomeClass { SomeInt = 3 , SomeString = "Three" }
} ;
collection . Humanize ( ) // "Specific String, Specific String, and Specific String"
collection . Humanize ( "or" ) // "Specific String, Specific String, or Specific String"
collection . Humanize ( FormatSomeClass ) // "SomeObject #1 - One, SomeObject #2 - Two, and SomeObject #3 - Three"
collection . Humanize ( sc => sc . SomeInt . Ordinalize ( ) , "or" ) // "1st, 2nd, or 3rd"将项目修剪,并跳过空白(NullorWhitespace)项目。这会导致清洁的逗号标点符号。 (如果有自定义格式化函数,则仅适用于格式的输出。)
您可以通过实现ICollectionFormatter并将其注册为Configurator.CollectionFormatters来提供自己的收集格式。
也有一些矿物质方法:
在考虑不规则和不可数用的单词时, Pluralize提供的输入倍增。
"Man" . Pluralize ( ) => "Men "
" string" . Pluralize ( ) => "strings"通常,您会在单个单词上称为Pluralize但是如果您不确定单词的奇异性,则可以使用可选的inputIsKnownToBeSingular参数调用该方法:
"Men" . Pluralize ( inputIsKnownToBeSingular : false ) => "Men "
" Man" . Pluralize ( inputIsKnownToBeSingular : false ) => "Men"
"string" . Pluralize ( inputIsKnownToBeSingular : false ) => "strings"与plurality参数的Pluralize已过时,并在版本2.0中被删除。
在考虑不规则和不可数用的单词时,奇异Singularize的输入奇异化了:
"Men" . Singularize ( ) => "Man "
" strings" . Singularize ( ) => "string"通常,您会在复数单词上称为Singularize ,但是如果您不确定该单词的多个单词,则可以使用可选的inputIsKnownToBePlural参数调用该方法:
"Men" . Singularize ( inputIsKnownToBePlural : false ) => "Man "
" Man" . Singularize ( inputIsKnownToBePlural : false ) => "Man"
"strings" . Singularize ( inputIsKnownToBePlural : false ) => "string"与plurality参数的Singularize已过时,并在版本2.0中被删除。
有时,您可能需要添加单个词汇/多元化词汇中的规则(以下示例已经在Inflector使用的DefaultVocabulary中):
// Adds a word to the vocabulary which cannot easily be pluralized/singularized by RegEx.
// Will match both "salesperson" and "person".
Vocabularies . Default . AddIrregular ( "person" , "people" ) ;
// To only match "person" and not "salesperson" you would pass false for the 'matchEnding' parameter.
Vocabularies . Default . AddIrregular ( "person" , "people" , matchEnding : false ) ;
// Adds an uncountable word to the vocabulary. Will be ignored when plurality is changed:
Vocabularies . Default . AddUncountable ( "fish" ) ;
// Adds a rule to the vocabulary that does not follow trivial rules for pluralization:
Vocabularies . Default . AddPlural ( "bus" , "buses" ) ;
// Adds a rule to the vocabulary that does not follow trivial rules for singularization
// (will match both "vertices" -> "vertex" and "indices" -> "index"):
Vocabularies . Default . AddSingular ( "(vert|ind)ices$" , "$1ex" ) ; 很多时候,您想称呼Singularize和Pluralize ,以一个单词的字数;例如“ 2个请求”,“ 3个人”。 ToQuantity将提供的单词带有数字,因此将单词相关或奇异化:
"case" . ToQuantity ( 0 ) => "0 cases"
"case" . ToQuantity ( 1 ) => "1 case"
"case" . ToQuantity ( 5 ) => "5 cases"
"man" . ToQuantity ( 0 ) => "0 men"
"man" . ToQuantity ( 1 ) => "1 man"
"man" . ToQuantity ( 2 ) => "2 men" ToQuantity可以弄清楚输入词是单数还是复数,并且会根据需要进行单一化或多元化:
"men" . ToQuantity ( 2 ) => "2 men"
"process" . ToQuantity ( 2 ) => "2 processes"
"process" . ToQuantity ( 1 ) => "1 process"
"processes" . ToQuantity ( 2 ) => "2 processes"
"processes" . ToQuantity ( 1 ) => "1 process"您还可以将第二个参数ShowQuantityAs传递给ToQuantity ,以指定您希望如何输出所提供的数量。默认值是ShowQuantityAs.Numeric ,这是我们在上面看到的。其他两个值是ShowQuantityAs.Words和ShowQuantityAs.None 。
"case" . ToQuantity ( 5 , ShowQuantityAs . Words ) => "five cases "
" case" . ToQuantity ( 5 , ShowQuantityAs . None ) => "cases"还有一个超负荷,使您可以格式化数字。您可以通过格式和要使用的文化。
"dollar" . ToQuantity ( 2 , "C0" , new CultureInfo ( "en-US" ) ) => "$2 dollars"
"dollar" . ToQuantity ( 2 , "C2" , new CultureInfo ( "en-US" ) ) => "$2.00 dollars"
"cases" . ToQuantity ( 12000 , "N0" ) => "12,000 cases" Ordinalize将数字变成用于表示有序序列的位置的序数字符串,例如第一,第二,第3,第四:
1 . Ordinalize ( ) => "1st"
5 . Ordinalize ( ) => "5th"您也可以在数字字符串上调用Ordinalize并获得相同的结果: "21".Ordinalize() => "21st"
Ordinalize也支持两种形式的语法性别。您可以将一个参数传递给Ordinalize ,以指定应该输入哪个性别的性别。可能的值是GrammaticalGender.Masculine , GrammaticalGender.Feminine和GrammaticalGender.Neuter :neuter:
// for Brazilian Portuguese locale
1 . Ordinalize ( GrammaticalGender . Masculine ) => "1º"
1 . Ordinalize ( GrammaticalGender . Feminine ) => "1ª"
1 . Ordinalize ( GrammaticalGender . Neuter ) => "1º"
"2" . Ordinalize ( GrammaticalGender . Masculine ) => "2º"
"2" . Ordinalize ( GrammaticalGender . Feminine ) => "2ª"
"2" . Ordinalize ( GrammaticalGender . Neuter ) => "2º"显然,这仅适用于某些文化。对于其他人传递性别或根本不通过的性别并没有任何影响的结果。
此外, Ordinalize支持变化某些培养物适用于句子中序数的位置。使用参数wordForm获得一个或另一个结果。可能的值是WordForm.Abbreviation and WordForm.Normal 。您可以将wordForm参数与性别结合在一起,但将此参数传递到不适用的情况下将不会对结果产生任何影响。
// Spanish locale
1 . Ordinalize ( WordForm . Abbreviation ) => "1.er" // As in "Vivo en el 1.er piso"
1 . Ordinalize ( WordForm . Normal ) => "1.º" // As in "He llegado el 1º"
"3" . Ordinalize ( GrammaticalGender . Feminine , WordForm . Abbreviation ) => "3.ª"
"3" . Ordinalize ( GrammaticalGender . Feminine , WordForm . Normal ) => "3.ª"
"3" . Ordinalize ( GrammaticalGender . Masculine , WordForm . Abbreviation ) => "3.er"
"3" . Ordinalize ( GrammaticalGender . Masculine , WordForm . Normal ) => "3.º" Titleize将输入词转换为标题壳;相当于"some title".Humanize(LetterCasing.Title)
Pascalize将输入词转换为上carcamelcase,还删除了下划线和空间:
"some_title for something" . Pascalize ( ) => "SomeTitleForSomething" Camelize行为相同以Pascalize ,但第一个字符是较低的情况:
"some_title for something" . Camelize ( ) => "someTitleForSomething" Underscore将输入单词与下划线分开:
"SomeTitle" . Underscore ( ) => "some_title" Dasherize和Hyphenate用字符串中的破折号取代下划线:
"some_title" . Dasherize ( ) => "some-title"
"some_title" . Hyphenate ( ) => "some-title" Kebaberize用连字符将输入单词分开,所有单词都转换为小写
"SomeText" . Kebaberize ( ) => "some-text"Humanizer提供了一种流利的API来处理DateTime和TimeSpan ,如下所示:
TimeSpan法:
2 . Milliseconds ( ) => TimeSpan . FromMilliseconds ( 2 )
2 . Seconds ( ) => TimeSpan . FromSeconds ( 2 )
2 . Minutes ( ) => TimeSpan . FromMinutes ( 2 )
2 . Hours ( ) => TimeSpan . FromHours ( 2 )
2 . Days ( ) => TimeSpan . FromDays ( 2 )
2 . Weeks ( ) => TimeSpan . FromDays ( 14 )一个月或一年没有流利的API,因为一个月可能有28至31天,一年可能是365或366天。
您可以使用这些方法来替换
DateTime . Now . AddDays ( 2 ) . AddHours ( 3 ) . AddMinutes ( - 5 )和
DateTime . Now + 2 . Days ( ) + 3 . Hours ( ) - 5 . Minutes ( )还有三类流利的方法可以处理DateTime :
In . TheYear ( 2010 ) // Returns the first of January of 2010
In . January // Returns 1st of January of the current year
In . FebruaryOf ( 2009 ) // Returns 1st of February of 2009
In . One . Second // DateTime.UtcNow.AddSeconds(1);
In . Two . SecondsFrom ( DateTime dateTime )
In . Three . Minutes // With corresponding From method
In . Three . Hours // With corresponding From method
In . Three . Days // With corresponding From method
In . Three . Weeks // With corresponding From method
In . Three . Months // With corresponding From method
In . Three . Years // With corresponding From method
On . January . The4th // Returns 4th of January of the current year
On . February . The ( 12 ) // Returns 12th of Feb of the current year以及一些扩展方法:
var someDateTime = new DateTime ( 2011 , 2 , 10 , 5 , 25 , 45 , 125 ) ;
// Returns new DateTime(2008, 2, 10, 5, 25, 45, 125) changing the year to 2008
someDateTime . In ( 2008 )
// Returns new DateTime(2011, 2, 10, 2, 25, 45, 125) changing the hour to 2:25:45.125
someDateTime . At ( 2 )
// Returns new DateTime(2011, 2, 10, 2, 20, 15, 125) changing the time to 2:20:15.125
someDateTime . At ( 2 , 20 , 15 )
// Returns new DateTime(2011, 2, 10, 12, 0, 0) changing the time to 12:00:00.000
someDateTime . AtNoon ( )
// Returns new DateTime(2011, 2, 10, 0, 0, 0) changing the time to 00:00:00.000
someDateTime . AtMidnight ( )显然,您也可以链接这些方法。例如On.November.The13th.In(2010).AtNoon + 5.Minutes()
Humanizer提供了一种流利的API,以更清晰的方式产生(通常很大)数字:
1.25 . Billions ( ) => 1250000000
3 . Hundreds ( ) . Thousands ( ) => 300000人体器可以使用ToWords扩展名将数字更改为单词:
1 . ToWords ( ) => "one"
10 . ToWords ( ) => "ten"
11 . ToWords ( ) => "eleven"
122 . ToWords ( ) => "one hundred and twenty-two"
3501 . ToWords ( ) => "three thousand five hundred and one"您还可以将第二个参数GrammaticalGender传递给ToWords ,以指定应该输入哪个性别的性别。可能的值是GrammaticalGender.Masculine , GrammaticalGender.Feminine和GrammaticalGender.Neuter 。
// for Russian locale
1 . ToWords ( GrammaticalGender . Masculine ) => "один"
1 . ToWords ( GrammaticalGender . Feminine ) => "одна"
1 . ToWords ( GrammaticalGender . Neuter ) => "одно" // for Arabic locale
1 . ToWords ( GrammaticalGender . Masculine ) => "واحد"
1 . ToWords ( GrammaticalGender . Feminine ) => "واحدة"
1 . ToWords ( GrammaticalGender . Neuter ) => "واحد"
( - 1 ) . ToWords ( ) => "ناقص واحد"显然,这仅适用于某些文化。对于其他人,通过性别对结果没有任何影响。
而且,可以明确指定要使用的文化。如果不是,则使用当前线程的当前UI文化。这是一个例子:
11 . ToWords ( new CultureInfo ( "en" ) ) => "eleven"
1 . ToWords ( GrammaticalGender . Masculine , new CultureInfo ( "ru" ) ) => "один"该方法的另一个过载使您可以通过布尔以删除可以在最后一个数字之前添加的“和”:
3501 . ToWords ( false ) => "three thousand five hundred one"
102 . ToWords ( false ) => "one hundred two"例如,此方法对于编写检查可能很有用。
此外, ToWords支持一些变化,某些文化根据句子中数字的位置而适用。使用参数wordForm获得一个或另一个结果。可能的值是WordForm.Abbreviation and WordForm.Normal 。该论点可以与上面提出的其余参数结合在一起。传递wordForm参数在不适用的何时将不会对结果产生任何影响。
// Spanish locale
21501 . ToWords ( WordForm . Abbreviation , GrammaticalGender . Masculine ) => "veintiún mil quinientos un"
21501 . ToWords ( WordForm . Normal , GrammaticalGender . Masculine ) => "veintiún mil quinientos uno"
21501 . ToWords ( WordForm . Abbreviation , GrammaticalGender . Feminine ) => "veintiuna mil quinientas una"
// English US locale
21501 . ToWords ( WordForm . Abbreviation , GrammaticalGender . Masculine , new CultureInfo ( "en-US" ) ) => "twenty-one thousand five hundred and one"这是一种ToWords与Ordinalize混合。您可以在数字上调用ToOrdinalWords ,以获取单词的数字表示!例如:
0 . ToOrdinalWords ( ) => "zeroth"
1 . ToOrdinalWords ( ) => "first"
2 . ToOrdinalWords ( ) => "second"
8 . ToOrdinalWords ( ) => "eighth"
10 . ToOrdinalWords ( ) => "tenth"
11 . ToOrdinalWords ( ) => "eleventh"
12 . ToOrdinalWords ( ) => "twelfth"
20 . ToOrdinalWords ( ) => "twentieth"
21 . ToOrdinalWords ( ) => "twenty first"
121 . ToOrdinalWords ( ) => "hundred and twenty first" ToOrdinalWords还支持语法性别。您可以将第二个参数传递给ToOrdinalWords以指定输出的性别。可能的值是GrammaticalGender.Masculine , GrammaticalGender.Feminine和GrammaticalGender.Neuter :
// for Brazilian Portuguese locale
1 . ToOrdinalWords ( GrammaticalGender . Masculine ) => "primeiro"
1 . ToOrdinalWords ( GrammaticalGender . Feminine ) => "primeira"
1 . ToOrdinalWords ( GrammaticalGender . Neuter ) => "primeiro"
2 . ToOrdinalWords ( GrammaticalGender . Masculine ) => "segundo"
2 . ToOrdinalWords ( GrammaticalGender . Feminine ) => "segunda"
2 . ToOrdinalWords ( GrammaticalGender . Neuter ) => "segundo" // for Arabic locale
1 . ToOrdinalWords ( GrammaticalGender . Masculine ) => "الأول"
1 . ToOrdinalWords ( GrammaticalGender . Feminine ) => "الأولى"
1 . ToOrdinalWords ( GrammaticalGender . Neuter ) => "الأول"
2 . ToOrdinalWords ( GrammaticalGender . Masculine ) => "الثاني"
2 . ToOrdinalWords ( GrammaticalGender . Feminine ) => "الثانية"
2 . ToOrdinalWords ( GrammaticalGender . Neuter ) => "الثاني"显然,这仅适用于某些文化。对于其他人,通过性别对结果没有任何影响。
而且,可以明确指定要使用的文化。如果不是,则使用当前线程的当前UI文化。这是一个例子:
10 . ToOrdinalWords ( new CultureInfo ( "en-US" ) ) => "tenth"
1 . ToOrdinalWords ( GrammaticalGender . Masculine , new CulureInfo ( "pt-BR" ) ) => "primeiro" ToOrdinalWords还支持一些变化,某些文化根据句子中的数字的位置而适用。使用参数wordForm获得一个或另一个结果。可能的值是WordForm.Abbreviation and WordForm.Normal 。将此论点与上面提出的其余论点相结合。传递wordForm参数在不适用的何时将不会对结果产生任何影响。
// Spanish locale
43 . ToOrdinalWords ( WordForm . Normal , GrammaticalGender . Masculine ) => "cuadragésimo tercero"
43 . ToOrdinalWords ( WordForm . Abbreviation , GrammaticalGender . Masculine ) => "cuadragésimo tercer"
43 . ToOrdinalWords ( WordForm . Abbreviation , GrammaticalGender . Feminine ) => "cuadragésima tercera"
// English locale
43 . ToOrdinalWords ( GrammaticalGender . Masculine , WordForm . Abbreviation , new CultureInfo ( "en" ) ) => "forty-third"这是序数的延伸
// for English UK locale
new DateTime ( 2015 , 1 , 1 ) . ToOrdinalWords ( ) => "1st January 2015"
new DateTime ( 2015 , 2 , 12 ) . ToOrdinalWords ( ) => "12th February 2015"
new DateTime ( 2015 , 3 , 22 ) . ToOrdinalWords ( ) => "22nd March 2015"
// for English US locale
new DateTime ( 2015 , 1 , 1 ) . ToOrdinalWords ( ) => "January 1st, 2015"
new DateTime ( 2015 , 2 , 12 ) . ToOrdinalWords ( ) => "February 12th, 2015"
new DateTime ( 2015 , 3 , 22 ) . ToOrdinalWords ( ) => "March 22nd, 2015" ToOrdinalWords还支持语法案例。您可以将第二个参数传递给ToOrdinalWords以指定输出的情况。 GrammaticalCase.Instrumental GrammaticalCase.Genitive GrammaticalGender.Prepositional GrammaticalCase.Dative GrammaticalCase.Nominative GrammaticalCase.Accusative
显然,这仅适用于某些文化。对于其他人来说,通过案件对结果没有任何影响。
扩展时间延长以使其人性化到时钟符号
// for English US locale
new TimeOnly ( 3 , 0 ) . ToClockNotation ( ) => "three o'clock"
new TimeOnly ( 12 , 0 ) . ToClockNotation ( ) => "noon"
new TimeOnly ( 14 , 30 ) . ToClockNotation ( ) => "half past two"
// for Brazilian Portuguese locale
new TimeOnly ( 3 , 0 ) . ToClockNotation ( ) => "três em ponto"
new TimeOnly ( 12 , 0 ) . ToClockNotation ( ) => "meio-dia"
new TimeOnly ( 14 , 30 ) . ToClockNotation ( ) => "duas e meia"人类者可以使用ToRoman扩展名将数字更改为罗马数字。数字1至10可以在罗马数字中表达,如下所示:
1 . ToRoman ( ) => "I"
2 . ToRoman ( ) => "II"
3 . ToRoman ( ) => "III"
4 . ToRoman ( ) => "IV"
5 . ToRoman ( ) => "V"
6 . ToRoman ( ) => "VI"
7 . ToRoman ( ) => "VII"
8 . ToRoman ( ) => "VIII"
9 . ToRoman ( ) => "IX"
10 . ToRoman ( ) => "X"也使用FromRoman扩展程序进行反向操作。
"I" . FromRoman ( ) => 1
"II" . FromRoman ( ) => 2
"III" . FromRoman ( ) => 3
"IV" . FromRoman ( ) => 4
"V" . FromRoman ( ) => 5请注意,只有小于4000的整数才能转换为罗马数字。
人体器可以使用ToMetric扩展名将数字更改为公制数字。数字1、1230和0.1可以在公制数字中表示:如下:
1d . ToMetric ( ) => "1"
1230d . ToMetric ( ) => "1.23k"
0.1d . ToMetric ( ) => "100m"也使用FromMetric扩展名进行反向操作。
"1" . FromMetric ( ) => 1
"1.23k" . FromMetric ( ) => 1230
"100m" . FromMetric ( ) => 0.1人体化包括辉煌的副标图书馆的港口。在ByteSize上进行了许多更改,以使与人体ByteSize API的互动更加容易,更一致。这是一些可以从数字转换为字节大小以及尺寸尺寸之间的一些示例:
var fileSize = ( 10 ) . Kilobytes ( ) ;
fileSize . Bits => 81920
fileSize . Bytes => 10240
fileSize . Kilobytes => 10
fileSize . Megabytes => 0.009765625
fileSize . Gigabytes => 9.53674316e-6
fileSize . Terabytes => 9.31322575e-9有几种扩展方法使您可以将数字转换为字节化实例:
3 . Bits ( ) ;
5 . Bytes ( ) ;
( 10.5 ) . Kilobytes ( ) ;
( 2.5 ) . Megabytes ( ) ;
( 10.2 ) . Gigabytes ( ) ;
( 4.7 ) . Terabytes ( ) ;您还可以使用+/-运算符添加/减去值,然后添加/减去方法:
var total = ( 10 ) . Gigabytes ( ) + ( 512 ) . Megabytes ( ) - ( 2.5 ) . Gigabytes ( ) ;
total . Subtract ( ( 2500 ) . Kilobytes ( ) ) . Add ( ( 25 ) . Megabytes ( ) ) ;一个ByteSize对象包含两个代表最大度量前缀符号和值的属性:
var maxFileSize = ( 10 ) . Kilobytes ( ) ;
maxFileSize . LargestWholeNumberSymbol ; // "KB"
maxFileSize . LargestWholeNumberValue ; // 10如果您想要字符串表示形式,则可以在ByteSize实例上互换致电ToString或Humanize :
7 . Bits ( ) . ToString ( ) ; // 7 b
8 . Bits ( ) . ToString ( ) ; // 1 B
( .5 ) . Kilobytes ( ) . Humanize ( ) ; // 512 B
( 1000 ) . Kilobytes ( ) . ToString ( ) ; // 1000 KB
( 1024 ) . Kilobytes ( ) . Humanize ( ) ; // 1 MB
( .5 ) . Gigabytes ( ) . Humanize ( ) ; // 512 MB
( 1024 ) . Gigabytes ( ) . ToString ( ) ; // 1 TB您还可以选择为预期字符串表示形式提供格式。格式化器可以包含要显示的值的符号: b , B , KB , MB , GB , TB 。该格式使用#.##作为默认格式的内置double.ToString方法,该格式将数字四舍五入到两个小数位:
var b = ( 10.505 ) . Kilobytes ( ) ;
// Default number format is #.##
b . ToString ( "KB" ) ; // 10.52 KB
b . Humanize ( "MB" ) ; // .01 MB
b . Humanize ( "b" ) ; // 86057 b
// Default symbol is the largest metric prefix value >= 1
b . ToString ( "#.#" ) ; // 10.5 KB
// All valid values of double.ToString(string format) are acceptable
b . ToString ( "0.0000" ) ; // 10.5050 KB
b . Humanize ( "000.00" ) ; // 010.51 KB
// You can include number format and symbols
b . ToString ( "#.#### MB" ) ; // .0103 MB
b . Humanize ( "0.00 GB" ) ; // 0 GB
b . Humanize ( "#.## B" ) ; // 10757.12 B如果您想要一个带有完整单词的字符串表示形式,则可以在ByteSize实例上调用ToFullWords :
7 . Bits ( ) . ToFullWords ( ) ; // 7 bits
8 . Bits ( ) . ToFullWords ( ) ; // 1 byte
( .5 ) . Kilobytes ( ) . ToFullWords ( ) ; // 512 bytes
( 1000 ) . Kilobytes ( ) . ToFullWords ( ) ; // 1000 kilobytes
( 1024 ) . Kilobytes ( ) . ToFullWords ( ) ; // 1 megabyte
( .5 ) . Gigabytes ( ) . ToFullWords ( ) ; // 512 megabytes
( 1024 ) . Gigabytes ( ) . ToFullWords ( ) ; // 1 terabyte没有一种Dehumanize方法将字符串表示形式转回一个ByteSize实例。但是,您可以在ByteSize上使用Parse和TryParse来做到这一点。像其他TryParse方法一样, ByteSize.TryParse返回boolean值,指示解析是否成功。如果分解该值,则将输出到提供的out参数:
ByteSize output ;
ByteSize . TryParse ( "1.5mb" , out output ) ;
// Invalid
ByteSize . Parse ( "1.5 b" ) ; // Can't have partial bits
// Valid
ByteSize . Parse ( "5b" ) ;
ByteSize . Parse ( "1.55B" ) ;
ByteSize . Parse ( "1.55KB" ) ;
ByteSize . Parse ( "1.55 kB " ) ; // Spaces are trimmed
ByteSize . Parse ( "1.55 kb" ) ;
ByteSize . Parse ( "1.55 MB" ) ;
ByteSize . Parse ( "1.55 mB" ) ;
ByteSize . Parse ( "1.55 mb" ) ;
ByteSize . Parse ( "1.55 GB" ) ;
ByteSize . Parse ( "1.55 gB" ) ;
ByteSize . Parse ( "1.55 gb" ) ;
ByteSize . Parse ( "1.55 TB" ) ;
ByteSize . Parse ( "1.55 tB" ) ;
ByteSize . Parse ( "1.55 tb" ) ;最后,如果您需要计算传输一定数量的字节的速率,则可以使用Per ByteSize的方法。 Per方法接受一个参数 - 字节的测量间隔;这是传输字节所需的时间。
Per方法返回具有Humanize方法的ByteRate类别。默认情况下,速率以秒为单位(例如MB/s)给出。但是,如果需要的话,可以将一个时间持续时间传递给Humanize替代间隔。有效的间隔为TimeUnit.Second , TimeUnit.Minute和TimeUnit.Hour 。每个间隔和示例字节率使用的示例如下。
var size = ByteSize . FromMegabytes ( 10 ) ;
var measurementInterval = TimeSpan . FromSeconds ( 1 ) ;
var text = size . Per ( measurementInterval ) . Humanize ( ) ;
// 10 MB/s
text = size . Per ( measurementInterval ) . Humanize ( TimeUnit . Minute ) ;
// 600 MB/min
text = size . Per ( measurementInterval ) . Humanize ( TimeUnit . Hour ) ;
// 35.15625 GB/hour您可以为人性化输出的字节部分指定格式:
19854651984 . Bytes ( ) . Per ( 1 . Seconds ( ) ) . Humanize ( "#.##" ) ;
// 18.49 GB/s人物包括将数字标准转换为单词的方法。标题可以是double ,而结果将是字符串。您可以选择是返回标题的完整表示(例如北部,东,南或西),简短表示(例如N,E,S,W)还是Unicode Arrow字符(例如,→,→,↓,←)。
360 . ToHeading ( ) ;
// N
720 . ToHeading ( ) ;
// N为了检索标题的完整版本,请使用以下调用:
180 . ToHeading ( HeadingStyle . Full ) ;
// south
360 . ToHeading ( HeadingStyle . Full ) ;
// north请注意,文本表示的最大偏差为11.25°。
最重要的方法具有超负荷,您可以提供一个CultureInfo对象,以确定要返回的本地化结果。
检索表示标题的箭头使用以下方法:
90 . ToHeadingArrow ( ) ;
// →
225 . ToHeadingArrow ( ) ;
// ↙标题的箭头表示的最大偏差为22.5°。
为了根据简短的文本表示(例如N,E,S,W)检索标题,可以使用以下方法:
"S" . FromShortHeading ( ) ;
// 180
"SW" . FromShortHeading ( ) ;
// 225人类可以使用Tupleize将整个数字更改为“元组”。例如:
1 . Tupleize ( ) ;
// single
3 . Tupleize ( ) ;
// triple
100 . Tupleize ( ) ;
// centuple数字1-10、100和1000将转换为“命名”元组(即“单个”,“ Double”等)。任何其他数字“ n”都将转换为“ n-tuple”。
人体器可以将时间单元转换为其符号:
TimeUnit . Day . ToSymbol ( ) ;
// d
TimeUnit . Week . ToSymbol ( ) ;
// week
TimeUnit . Year . ToSymbol ( ) ;
// y 这只是基准,您可以使用它来简化日常工作。例如,在ASP.NET MVC中,我们继续在ViewModel属性上chucking Display属性,以便HtmlHelper可以为我们生成正确的标签;但是,就像枚举一样,在绝大多数情况下,我们只需要属性名称中的单词之间的空间 - 那么为什么不使用"string".Humanize
您可能会在代码中找到ASP.NET MVC示例(尽管该项目被从解决方案文件中排除,以使Nuget软件包也可用于.NET 3.5)。
这是使用我称为hansizermetadataprovider的自定义DataAnnotationsModelMetadataProvider来实现的。它足够小,可以在这里重复;所以我们去:
using System ;
using System . Collections . Generic ;
using System . ComponentModel ;
using System . ComponentModel . DataAnnotations ;
using System . Linq ;
using System . Web . Mvc ;
using Humanizer ;
public class HumanizerMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata (
IEnumerable < Attribute > attributes ,
Type containerType ,
Func < object > modelAccessor ,
Type modelType ,
string propertyName )
{
var propertyAttributes = attributes . ToList ( ) ;
var modelMetadata = base . CreateMetadata ( propertyAttributes , containerType , modelAccessor , modelType , propertyName ) ;
if ( IsTransformRequired ( modelMetadata , propertyAttributes ) )
modelMetadata . DisplayName = modelMetadata . PropertyName . Humanize ( ) ;
return modelMetadata ;
}
private static bool IsTransformRequired ( ModelMetadata modelMetadata , IList < Attribute > propertyAttributes )
{
if ( string . IsNullOrEmpty ( modelMetadata . PropertyName ) )
return false ;
if ( propertyAttributes . OfType < DisplayNameAttribute > ( ) . Any ( ) )
return false ;
if ( propertyAttributes . OfType < DisplayAttribute > ( ) . Any ( ) )
return false ;
return true ;
}
}该课程称基类提取元数据,然后(如果需要)使属性名称人性化。它正在检查该属性是否已经在其上具有DisplayName或Display属性,在这种情况下,元数据提供商将尊重该属性并将属性留下。对于其他属性,它将使属性名称人性化。仅此而已。
现在,您需要向ASP.NET MVC注册此元数据提供商。确保使用System.Web.Mvc.ModelMetadataProviders ,而不是System.Web.ModelBinding.ModelMetadataProviders :
ModelMetadataProviders . Current = new HumanizerMetadataProvider ( ) ;...现在您可以替换:
public class RegisterModel
{
[ Display ( Name = "User name" ) ]
public string UserName { get ; set ; }
[ Display ( Name = "Email address" ) ]
public string EmailAddress { get ; set ; }
[ Display ( Name = "Confirm password" ) ]
public string ConfirmPassword { get ; set ; }
}和:
public class RegisterModel
{
public string UserName { get ; set ; }
public string EmailAddress { get ; set ; }
public string ConfirmPassword { get ; set ; }
}...“元数据人物”将照顾其余的。
无需提及,如果您想要标签标题套管,则可以通过Transform将方法链接:
modelMetadata . DisplayName = modelMetadata . PropertyName . Humanize ( ) . Transform ( To . TitleCase ) ; Humanizer是便携式班级库。如果您尝试在MVC视图中使用PCL,则目前存在问题,因为MVC视图与常规项目没有相同的构建系统。您必须在web.config文件中指定所有引用,包括通常自动添加的项目系统。
如果您遇到错误,说您必须添加对System.Runtime或System.Globalization引用。解决方案是将合同引用添加到您的web.config ,如下所示。请注意,这适用于您在MVC视图中使用的任何PCL,而不仅仅是人类化合物。
人类化项目是由Azure DevOps连续构建和测试的(此处的更多详细信息)。这也适用于提取请求。提交公关后不久,您可以检查PR上的构建状态和测试状态通知。
CI服务器上的当前构建状态是
以下是相关开源项目的列表:
如果使用Resharper,则可以在人类器中提供人体化的注释。通量软件包,您可以通过Resmanter Extension Manager获得。这些注释尚未涵盖整个图书馆,但始终欢迎拉动请求!
Powershell Humanizer是包裹人体化合物的Powershell模块。
Humanizer.jvm是针对.NET的人体器框架的改编,该框架是为JVM制作的,并用Kotlin编写。 Humanizer.jvm满足您的所有JVM操纵和显示字符串,枚举,日期,时间,时间,数量,数量和数量的需求。
Humanizer.Node是人类器框架的打字稿端口。
泰隆·里斯基克(Tyrone Rieschiek)创建的图标