.NET 幫助

Humanizer C#(開發人員如何使用)

發佈 2024年7月1日
分享:

Humanizer 是一個功能強大且靈活的 .NET 程式庫,它簡化並人性化了處理數據的過程,特別是當需要以用戶友好的格式顯示信息時。不論您是否需要將日期轉換為相對時間字串 (3 天前)將字詞複數化、將數字格式化為單詞、或處理枚舉、顯示字串、以提供自定義描述的 Pascal 大小寫字串作為句子,將帶有底線的輸入字串轉換為正常的標題大小寫字串,和長文本截斷,Humanizer 在 C#.NET 中提供大量工具和擴展方法來優雅地處理這些任務,將去人性化的輸入字串轉換成句子。

在本文中,我們將詳述 Humanizer 在 C# 中的使用教程。我們還將討論如何使用 Humanizer 和 IronPDF for C# PDF Library 生成 PDF 文件。

在C#中設置Humanizer

要開始使用Humanizer,您需要通過NuGet安裝該庫。在您的項目中,您可以通過包管理器控制台使用以下命令來完成此操作:

Install-Package Humanizer
Install-Package Humanizer
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package Humanizer
VB   C#

或者,如果您在使用 .NET Core CLI,您可以使用以下命令添加 Humanizer:

dotnet add package Humanizer

安裝後,您可以透過在您的 C# 文件中包含適當的命名空間開始使用 Humanizer:

using Humanizer;
using Humanizer;
Imports Humanizer
VB   C#

人性化日期和時間

Humanizer最常見的用途之一是使用Humanize方法將日期和時間轉換成人類可讀的格式、時間間隔、數字和數量。這對於顯示相對時間(例如「2小時前」或「5天後」)特別有用。

示例:人性化相對時間

DateTime pastDate = DateTime.Now.AddDays(-3);
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
DateTime pastDate = DateTime.Now.AddDays(-3);
string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"
DateTime futureDate = DateTime.Now.AddHours(5);
string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"
Dim pastDate As DateTime = DateTime.Now.AddDays(-3)
Dim humanizedTime As String = pastDate.Humanize() ' Output: "3 days ago"
Dim futureDate As DateTime = DateTime.Now.AddHours(5)
Dim futureHumanizedTime As String = futureDate.Humanize() ' Output: "in 5 hours"
VB   C#

Humanizer 擴充方法自動處理不同的時間單位,甚至調整以符合語法正確性。

Humanizer C#(對開發者的作用):圖1 - 人性化相對時間輸出

人性化時間跨度

Humanizer 也可以將 TimeSpan 物件人性化,使顯示持續時間變得易於閱讀。

範例:人性化的時間跨度

TimeSpan timeSpan = TimeSpan.FromMinutes(123);
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
TimeSpan timeSpan = TimeSpan.FromMinutes(123);
string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
Dim timeSpan As TimeSpan = System.TimeSpan.FromMinutes(123)
Dim humanizedTimeSpan As String = timeSpan.Humanize(2) ' Output: "2 hours, 3 minutes"
VB   C#

Humanizer C#(開發人員如何運作):圖2 - 將TimeSpan輸出人性化

處理數字

Humanizer 提供了幾種方法將數字轉換為人類可讀的文字並處理序數。

範例:將數字轉換為文字

int number = 123;
string words = number.ToWords(); // Output: "one hundred and twenty-three"
int number = 123;
string words = number.ToWords(); // Output: "one hundred and twenty-three"
Dim number As Integer = 123
Dim words As String = number.ToWords() ' Output: "one hundred and twenty-three"
VB   C#

Humanizer C#(對開發人員的作用):圖3 - 數字轉換為文字輸出

範例:將數字轉換為序數

int number = 21;
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
int number = 21;
string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
Dim number As Integer = 21
Dim ordinal As String = number.ToOrdinalWords() ' Output: "twenty-first"
VB   C#

Humanizer C#(對開發者的作用):圖 4 - 數字轉換為序數輸出

複數化與單數化

Humanizer 使將單詞在單數和複數形式之間轉換變得簡單,這對於根據數量動態生成長文本非常有用。

範例:使單詞變成複數和單數

string singular = "car";
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
string singularForm = word.Singularize(); // Output: "person"
string singular = "car";
string plural = singular.Pluralize(); // Output: "cars"
string word = "people";
string singularForm = word.Singularize(); // Output: "person"
Dim singular As String = "car"
Dim plural As String = singular.Pluralize() ' Output: "cars"
Dim word As String = "people"
Dim singularForm As String = word.Singularize() ' Output: "person"
VB   C#

Humanizer 也能處理不規則的複數化和單數化,使其適用於各種情境。

Humanizer C#(開發人員操作方式): 圖5 - 複數化和單數化輸出

格式化枚舉

枚舉經常在 C# 應用程式中用來表示一組具名常數。Humanizer 可以將枚舉值轉換為人類可讀的字串。

示例:Humanizing Enums

MyEnum enumValue = MyEnum.FirstValue;
string humanizedEnum = enumValue.Humanize();
System.Console.WriteLine(humanizedEnum);
public enum MyEnum
{
    FirstValue,
    SecondValue
} // Output: "First value"
MyEnum enumValue = MyEnum.FirstValue;
string humanizedEnum = enumValue.Humanize();
System.Console.WriteLine(humanizedEnum);
public enum MyEnum
{
    FirstValue,
    SecondValue
} // Output: "First value"
Private enumValue As MyEnum = MyEnum.FirstValue
Private humanizedEnum As String = enumValue.Humanize()
System.Console.WriteLine(humanizedEnum)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'public enum MyEnum
'{
'	FirstValue,
'	SecondValue
'} ' Output: "First value"
VB   C#

此方法對於在 UI 中顯示對使用者友好的標籤特別有用。

開發者的Humanizer C#(運作原理):圖6 - Humanize Enum輸出

人性化位元組大小

Humanizer 的另一個方便功能是能夠人性化位元組大小,將大型位元組值轉換為可讀格式,例如 KB、MB 或 GB。

範例:人性化字節大小

long bytes = 1048576;
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
long bytes = 1048576;
string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"
Dim bytes As Long = 1048576
Dim humanizedBytes As String = bytes.Bytes().Humanize() ' Output: "1 MB"
VB   C#

Humanizer C#(開發人員的工作原理):圖7 - 人性化字節大小輸出

高級場景

Humanizer不僅限於上述基本場景。它支持多種高級功能,例如Truncate方法以及多種語言和擴展。

範例:人性化的 DateTime 偏移量

Humanizer 也能處理 DateTimeOffset,這對處理時區的應用程式非常有用。

DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"
Dim dateTimeOffset As DateTimeOffset = System.DateTimeOffset.Now.AddDays(-2)
Dim humanizedDateTimeOffset As String = dateTimeOffset.Humanize() ' Output: "2 days ago"
VB   C#

Humanizer C#(對開發人員的運作原理):圖8 - 人性化 DateTime Offset 輸出

性能考量

Humanizer 雖然被設計為高效能的,但其性能依賴於使用方式。對於需要高性能的應用程序,特別是處理大型數據集或實時處理的應用程序,更需要考慮頻繁使用Humanizer運算的影響。

IronPDF for C

IronPDF 是一個為 .NET 應用程式設計的全面 PDF 生成和操作庫。它使開發人員可以輕鬆創建、讀取、編輯和提取 PDF 文件中的內容。IronPDF 旨在易於使用,提供了廣泛的功能,包括將 HTML 轉換為 PDF、合併文件、添加水印等。其多功能性和強大功能使其成為在 C# 專案中處理 PDF 文檔的絕佳選擇。

通過NuGet套件管理器安裝IronPDF

按照以下步驟使用NuGet套件管理器安裝IronPDF:

  1. 在Visual Studio中打開您的項目

    • 啟動Visual Studio並打開您現有的C#項目或創建一個新項目。
  2. 打開NuGet套件管理器

    • 在解決方案資源管理器中右鍵點擊您的項目。
    • 從上下文菜單中選擇「管理NuGet套件...」。

Humanizer C#(開發人員操作說明):圖 9 - NuGet 套件管理器

  1. 安裝 IronPDF

    • 在 NuGet 套件管理器中,轉到 "瀏覽" 標籤。
    • 搜尋 IronPDF
    • 從搜尋結果中選擇 IronPDF 套件。
    • 點擊 "安裝" 按鈕,將 IronPDF 添加到您的項目中。

Humanizer C#(如何為開發人員工作):圖10 - IronPDF

按照以下步驟,IronPDF 將安裝並且可以在您的 C# 專案中使用,讓您可以利用其強大的 PDF 操作功能。

C# Humanizer 和 IronPDF 代碼範例

using Humanizer;
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Instantiate Renderer
        var renderer = new ChromePdfRenderer();
        List<string> content = GenerateHumanizedContent();
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Iterate over each item in the List and add it to the HTML string
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Export to a file or stream
        pdf.SaveAs("output.pdf");
    }

    static List<string> GenerateHumanizedContent()
    {
        List<string> content = new List<string>();

        // DateTime examples
        DateTime pastDate = DateTime.Now.AddDays(-3);
        DateTime futureDate = DateTime.Now.AddHours(5);
        content.Add($"DateTime.Now: {DateTime.Now}");
        content.Add($"3 days ago: {pastDate.Humanize()}");
        content.Add($"In 5 hours: {futureDate.Humanize()}");

        // TimeSpan examples
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}");

        // Number examples
        int number = 12345;
        content.Add($"Number 12345 in words: {number.ToWords()}");
        content.Add($"Ordinal of 21: {21.ToOrdinalWords()}");

        // Pluralization examples
        string singular = "car";
        content.Add($"Plural of 'car': {singular.Pluralize()}");
        string plural = "children";
        content.Add($"Singular of 'children': {plural.Singularize()}");

        // Byte size examples
        long bytes = 1048576;
        content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}");

        return content;
    }
}
using Humanizer;
using IronPdf;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Instantiate Renderer
        var renderer = new ChromePdfRenderer();
        List<string> content = GenerateHumanizedContent();
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Iterate over each item in the List and add it to the HTML string
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Export to a file or stream
        pdf.SaveAs("output.pdf");
    }

    static List<string> GenerateHumanizedContent()
    {
        List<string> content = new List<string>();

        // DateTime examples
        DateTime pastDate = DateTime.Now.AddDays(-3);
        DateTime futureDate = DateTime.Now.AddHours(5);
        content.Add($"DateTime.Now: {DateTime.Now}");
        content.Add($"3 days ago: {pastDate.Humanize()}");
        content.Add($"In 5 hours: {futureDate.Humanize()}");

        // TimeSpan examples
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}");

        // Number examples
        int number = 12345;
        content.Add($"Number 12345 in words: {number.ToWords()}");
        content.Add($"Ordinal of 21: {21.ToOrdinalWords()}");

        // Pluralization examples
        string singular = "car";
        content.Add($"Plural of 'car': {singular.Pluralize()}");
        string plural = "children";
        content.Add($"Singular of 'children': {plural.Singularize()}");

        // Byte size examples
        long bytes = 1048576;
        content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}");

        return content;
    }
}
Imports Humanizer
Imports IronPdf
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		' Instantiate Renderer
		Dim renderer = New ChromePdfRenderer()
		Dim content As List(Of String) = GenerateHumanizedContent()
		Dim htmlContent As String = "<h1>Humanizer Examples</h1><ul>"

		' Iterate over each item in the List and add it to the HTML string
		For Each item In content
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"

		' Create a PDF from an HTML string using C#
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

		' Export to a file or stream
		pdf.SaveAs("output.pdf")
	End Sub

	Private Shared Function GenerateHumanizedContent() As List(Of String)
		Dim content As New List(Of String)()

		' DateTime examples
		Dim pastDate As DateTime = DateTime.Now.AddDays(-3)
		Dim futureDate As DateTime = DateTime.Now.AddHours(5)
		content.Add($"DateTime.Now: {DateTime.Now}")
		content.Add($"3 days ago: {pastDate.Humanize()}")
		content.Add($"In 5 hours: {futureDate.Humanize()}")

		' TimeSpan examples
		Dim timeSpan As TimeSpan = System.TimeSpan.FromMinutes(123)
		content.Add($"TimeSpan of 123 minutes: {timeSpan.Humanize()}")

		' Number examples
		Dim number As Integer = 12345
		content.Add($"Number 12345 in words: {number.ToWords()}")
		content.Add($"Ordinal of 21: {21.ToOrdinalWords()}")

		' Pluralization examples
		Dim singular As String = "car"
		content.Add($"Plural of 'car': {singular.Pluralize()}")
		Dim plural As String = "children"
		content.Add($"Singular of 'children': {plural.Singularize()}")

		' Byte size examples
		Dim bytes As Long = 1048576
		content.Add($"1,048,576 bytes: {bytes.Bytes().Humanize()}")

		Return content
	End Function
End Class
VB   C#

Humanizer C#(它是如何為開發人員工作的):圖11 - PDF輸出

結論

Humanizer 是 .NET 開發人員創建信息以使用者友善和人類可讀格式呈現的重要函式庫。其廣泛的功能範圍從日期和時間的人性化到數字和枚舉格式化,使其成為一個提高應用程式可用性的多功能工具。通過利用 Humanizer,開發人員可以節省在實施自訂格式邏輯上的時間和精力,確保他們的應用程式能更有效地向終端使用者傳達數據。

同樣地,IronPDF 提供了全面的 PDF 生成和操作功能,使其成為在 C# 專案中創建和處理 PDF 文檔的極佳選擇。Humanizer 和 IronPDF 結合使用,可以顯著提升 .NET 應用程式的功能和呈現效果。有關 IronPDF 授權的詳細信息,請參考 IronPDF 授權頁面。要進一步探索,請查看我們的 HTML 轉 PDF 詳細教程。

< 上一頁
TensorFlow .NET(它對開發者的運作方式)
下一個 >
OpenAPI .NET(適用於開發人員的工作原理)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >