開源項目Humanizer介紹

来源:https://www.cnblogs.com/88223100/archive/2020/03/19/Humanizer.html
-Advertisement-
Play Games

Humanizer 能夠滿足您所有.Net關於操作和展示以下類型的需求,包括字元串、枚舉、日期、時間、時間跨度、數字和數量。它採用 MIT 進行授權分發。 ...


  Humanizer 能夠滿足您所有.Net關於操作和展示以下類型的需求,包括字元串、枚舉、日期、時間、時間跨度、數字和數量。它採用 MIT 進行授權分發。

 

1、人性化字元串

人性化的字元串擴展名使您可以將原本由電腦處理的字元串轉換為更具可讀性的人性化字元串。 它的基礎是在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"

LetterCasing API和接受它的方法是V0.2時代的遺留物,將來會不推薦使用。 代替的是,您可以使用下麵介紹的Transform方法。

 

2、非人性化的字元串

就像您可以將電腦友好的字元串人性化為人類友好的字元串一樣,您也可以將人類友好的字元串人性化為電腦友好的字元串:

"Pascal case input string is turned into sentence".Dehumanize() => "PascalCaseInputStringIsTurnedIntoSentence"

 

3、轉換字元串

有一種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是To類的公共靜態屬性,它返回私有ToLowerCase類的實例,該實例實現IStringTransformer並知道如何將字元串轉換為小寫。

與ApplyCase和LetterCasing相比,使用Transform和IStringTransformer的好處是LetterCasing是枚舉,並且您只能使用框架中的內容,而IStringTransformer是可以在代碼庫中一次實現並與Transform方法一起使用的介面,從而可以輕鬆擴展 。

 

4、截斷字元串

您可以使用Truncate方法截斷字元串:

"Long text to truncate".Truncate(10) => "Long text…"

預設情況下,“ ...”字元用於截斷字元串。 使用'...'字元而不是“ ...”的優點是前者僅使用一個字元,因此允許在截斷之前顯示更多文本。 如果需要,還可以提供自己的截斷字元串:

"Long text to truncate".Truncate(10, "---") => "Long te---"

預設的截斷策略Truncator.FixedLength是將輸入字元串截斷為特定長度,包括截斷字元串的長度。 還有兩種其他的截斷器策略:一種用於固定數量的(字母數字)字元,另一種用於固定數量的單詞。 要在截斷時使用特定的截斷器,前面示例中顯示的兩個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"

 

5、格式化字元串

您可以使用FormatWith()方法設置字元串格式:

"To be formatted -> {0}/{1}.".FormatWith(1, "A") => "To be formatted -> 1/A."

這是基於String.Format的擴展方法,因此確切的規則適用於它。 如果format為null,則將引發ArgumentNullException。 如果傳遞的參數數目較少,則會引發String.FormatException異常。

您還可以指定區域性以顯式用作FormatWith()方法的第一個參數:

"{0:N2}".FormatWith(new CultureInfo("ru-RU"), 6666.66) => "6 666,66"

如果未指定區域性,則使用當前線程的當前區域性。

 

6、人性化枚舉

直接在枚舉成員上調用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作為自定義描述。 應用於具有字元串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

希望這將有助於避免亂定義帶有不必要屬性的枚舉!

 

7、使枚舉非人性化

將字元串人性化,使其原本是人性化的枚舉! 該API如下所示:

public static TTargetEnum DehumanizeTo<TTargetEnum>(this string input)

用法是:

"Member without description attribute".DehumanizeTo<EnumUnderTest>() => EnumUnderTest.MemberWithoutDescriptionAttribute

就像Humanize API一樣,它使用Description屬性。 您無需提供在人性化過程中提供的外殼:它可以弄清楚。

當在編譯時不知道原始Enum時,還有一個非泛型對應項:

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。

 

8、人性化DateTime

您可以對DateTime或DateTimeOffset的實例進行人性化,並返回一個字元串,該字元串告訴您時間上的倒退或前進時間:

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

日期沒有非人性化,因為人性化是有損的轉換,並且人類友好的日期是不可逆的。

 

9、人性化的時間跨度

您可以在TimeSpan上調用Humanize以獲得人性化的表示形式:

TimeSpan.FromMilliseconds(1).Humanize() => "1 millisecond"
TimeSpan.FromMilliseconds(2).Humanize() => "2 milliseconds"
TimeSpan.FromDays(1).Humanize() => "1 day"
TimeSpan.FromDays(16).Humanize() => "2 weeks"

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"

預設情況下,使用精度參數時,空時間單位不計入返回值的精度。 如果您不需要這種行為,則可以將重載的TimeSpan.Humanize方法與countEmptyUnits參數一起使用。 前導的空時間單位永遠不會計數。 這是顯示空單位計數的區別的示例:

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,則該方法將返回“ no time”。 例如:

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中的數字轉換為單詞:

TimeSpan.FromMilliseconds(1299630020).Humanize(3,toWords:true)=>“兩個星期,一天,一個小時”

 

10、人性化集合

您可以在任何IEnumerable上調用Humanize,以獲取格式正確的字元串,該字元串表示集合中的對象。 預設情況下,將在每個項目上調用ToString()以獲取其表示形式,但是可以將格式化函數傳遞給Humanize。 此外,提供了一個預設的分隔符(英語中為“ and”),但是可以將其他分隔符傳遞給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註冊它來提供自己的集合格式化程式。

 

11、Inflector 方法

還有一些 inflector 方法:

 

複數

在考慮不規則和不可數詞的情況下,將提供的輸入複數化:

"Man".Pluralize() => "Men"
"string".Pluralize() => "strings"

通常,您將對單個單詞調用Pluralize,但如果不確定單詞的奇異性,則可以使用可選的inputIsKnownToBeSingular參數調用該方法:

"Men".Pluralize(inputIsKnownToBeSingular: false) => "Men"
"Man".Pluralize(inputIsKnownToBeSingular: false) => "Men"
"string".Pluralize(inputIsKnownToBeSingular: false) => "strings"

具有複數參數的Pluralize重載已過時,在2.0版中已刪除。

 

單數化

單數將提供的輸入單數化,同時考慮不規則和不可數的單詞:

"Men".Singularize() => "Man"
"strings".Singularize() => "string"

通常,您會在一個複數單詞上調用單數化,但是如果不確定該單詞的複數形式,則可以使用可選的inputIsKnownToBePlural參數調用該方法:

"Men".Singularize(inputIsKnownToBePlural: false) => "Man"
"Man".Singularize(inputIsKnownToBePlural: false) => "Man"
"strings".Singularize(inputIsKnownToBePlural: false) => "string"

具有複數參數的Singularize重載已過時,並且在2.0版中已刪除。

 

12、添加單詞

有時,您可能需要從單數/複數辭彙表中添加一條規則(以下示例已在Inflector使用的預設辭彙表中):

// 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");

到數量

很多時候,您想調用單數化和複數化為單詞加上數字。 例如 “ 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"

序數化

序數化將數字轉換為序數字元串,用於表示有序序列(例如1st,2nd,3rd,4th)中的位置:

1.Ordinalize() => "1st"
5.Ordinalize() => "5th"

您還可以在數字字元串上調用Ordinalize並獲得相同的結果:“ 21” .Ordinalize()=>“ 21st”

序數化還支持兩種形式的語法性別。 您可以將一個參數傳遞給Ordinalize,以指定數字應以哪種性別輸出。可能的值為GrammaticalGender.Masculine,GrammmicalGender.Feminine和GrammaticalGender.Neuter:

// for Brazilian Portuguese locale
1.Ordinalize(GrammaticalGender.Masculine) => ""
1.Ordinalize(GrammaticalGender.Feminine) => ""
1.Ordinalize(GrammaticalGender.Neuter) => ""
"2".Ordinalize(GrammaticalGender.Masculine) => ""
"2".Ordinalize(GrammaticalGender.Feminine) => ""
"2".Ordinalize(GrammaticalGender.Neuter) => ""

顯然,這僅適用於某些文化。 對於其他通過性別或根本不通過的人,結果沒有任何區別。

標題化

Titleize將輸入的單詞轉換為Title大小寫; 等效於“某些標題”。Humanize(LetterCasing.Title)

Pascalize

Pascalize將輸入的單詞轉換為UpperCamelCase,還刪除下劃線和空格:

"some_title for something".Pascalize() => "SomeTitleForSomething"

Camelize

Camelize的行為與Pascalize相同,但第一個字元為小寫:

"some_title for something".Camelize() => "someTitleForSomething"

下劃線

Underscore用下劃線分隔輸入的單詞:

"SomeTitle".Underscore() => "some_title"

Dasherize & Hyphenate

Dasherize和Hyphenate用下劃線替換下劃線:

"some_title".Dasherize() => "some-title"
"some_title".Hyphenate() => "some-title"
Kebaberize Kebaberize用連字元分隔輸入的單詞,所有單詞都轉換為小寫
"SomeText".Kebaberize() => "some-text"

 

13、流利的日期

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(
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 01-多線程的引入 如果程式只有一條執行路徑,那麼該程式就是單線程程式 如果程式有多條執行程式,那麼該程式就是多線程程式 02-進程概述及多進程的意義 要想瞭解多線程,必須先瞭解線程,而要想瞭解線程,必須先瞭解進程,因為線程是依賴於進程而存在。 進程:就是正在運行的程式。 進程是系統進行資源分配和調 ...
  • @2020.3.19 # 作業要求:下述所有代碼畫圖以及分析代碼執行流程# 1、以定義階段為準,先畫出名稱空間的嵌套關係圖# 2、然後找到調用函數的位置,寫出函數調用時代碼的執行過程,涉及到名字的查找時,參照1中畫好的嵌套圖,標明查找順序,一層一層直到找到位置 # 題目一 input=333 def ...
  • 前幾天微軟收購npm的新聞對於軟粉來收很是振奮。微軟收購npm很可能是為了加強Github Packages。目前Github,Typescript,VSCode,npm這些開源社區的重磅工具全部都在微軟旗下,顯示出了微軟對開源的態度,微軟已經不是以前那個封閉的微軟。Github推出Github P ...
  • 基於 Roslyn 實現一個簡單的條件解析引擎 Intro 最近在做一個勛章的服務,我們想定義一些勛章的獲取條件,滿足條件之後就給用戶頒發一個勛章,定義條件的時候會定義需要哪些參數,參數的類型,獲取勛章的時候會提供鎖需要的參數,有一些內置的參數,內置的參數解析器(ParamResolver)。 最後 ...
  • 作業:輸入某年某月某日,判斷這一天是這一年的第幾天?。要求:需寫一個函數,給定年月 日,求的該天處於該年的第幾天。然後在Main函數中測試。 思路: ①需要有兩個函數。一個主函數,一個Date函數用來計算天數。 ②在主函數裡面利用控制台輸入年月日,然後在調用Date函數. 由於調用函數了就傳值了,調 ...
  • asp.net core應用常常要通過nginx來反向代理, 普通的web api配置asp.net core反向代理比較常見, 如果在應用中集成了signalr, 如何使用nginx來反代呢? ...
  • 使用UUID或者GUID產生的ID沒有規則 Snowflake演算法是Twitter的工程師為實現遞增而不重覆的ID實現的 概述 分散式系統中,有一些需要使用全局唯一ID的場景,這種時候為了防止ID衝突可以使用36位的UUID,但是UUID有一些缺點,首先他相對比較長,另外UUID一般是無序的。有些時 ...
  • 帶著問題去思考!大家好。 修飾符 修飾符有什麼作用呢?它是什麼東西呢? 首先修飾符有四種 private[ˈpraɪvət] protected [prə'tektɪd] internal [ɪnˈtɜːnl] public [ˈpʌblɪk] 他們的特效依次是: private 修飾符用於設置類或 ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...