人物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)創建的圖標