1. 程式人生 > 其它 >Humanizer 操作和展示以下型別的需求,包括字串、列舉、日期、時間、時間跨度、數字和數量。

Humanizer 操作和展示以下型別的需求,包括字串、列舉、日期、時間、時間跨度、數字和數量。

一、使用:直接NuGet直接搜尋Humanizer下載即可

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
      
參考:https://www.xin3721.com/articlecsharp/net19608.html