跳至頁尾內容
.NET 幫助

Humanizer C#(開發者使用方法)

Humanizer 是一個功能強大且靈活的 .NET 程式庫,它簡化了資料處理過程,使其更加人性化,尤其是以使用者友好的格式顯示資訊。 無論您需要將日期轉換為相對時間字符串("3 天前")、將單詞複數化、將數字格式化為單詞,還是處理枚舉、顯示字符串、將 Pascal 格式的輸入字符串轉換為帶有自定義描述的句子、將帶下劃線的輸入字符串轉換為正常的標題格式字符串以及截斷長文本,Humanizer 都提供了大量的工具和字符串任務,NET 可以處理句子,可以在其中一個優雅地處理句子的人,優雅地處理。

本文將詳細說明 C# 中的 Humanizer 實作方法。 我們也將討論如何使用 Humanizer 和 IronPDF 為 C# PDF 庫產生 PDF 文件。

在 C# 中設定 Humanizer

要開始使用 Humanizer,您需要透過 NuGet 安裝程式庫。 在您的專案中,您可以透過套件管理器控制台使用以下命令來完成此操作:

Install-Package Humanizer

或者,如果您使用的是 .NET Core CLI,則可以使用以下命令新增 Humanizer:

dotnet add package Humanizer

安裝完成後,您可以透過 C# 檔案中包含對應的命名空間來開始使用 Humanizer:

using Humanizer;
using Humanizer;
$vbLabelText   $csharpLabel

日期和時間的人性化

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

例:人性化相對時間

using System;

class HumanizerDemo
{
    static void Main()
    {
        DateTime pastDate = DateTime.Now.AddDays(-3);
        // Humanize the past date, which converts it to a relative time format
        string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"

        DateTime futureDate = DateTime.Now.AddHours(5);
        // Humanize the future date, presenting it in relative time
        string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"

        Console.WriteLine("Humanized Past Date: " + humanizedTime);
        Console.WriteLine("Humanized Future Date: " + futureHumanizedTime);
    }
}
using System;

class HumanizerDemo
{
    static void Main()
    {
        DateTime pastDate = DateTime.Now.AddDays(-3);
        // Humanize the past date, which converts it to a relative time format
        string humanizedTime = pastDate.Humanize(); // Output: "3 days ago"

        DateTime futureDate = DateTime.Now.AddHours(5);
        // Humanize the future date, presenting it in relative time
        string futureHumanizedTime = futureDate.Humanize(); // Output: "in 5 hours"

        Console.WriteLine("Humanized Past Date: " + humanizedTime);
        Console.WriteLine("Humanized Future Date: " + futureHumanizedTime);
    }
}
$vbLabelText   $csharpLabel

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

! C#人性化工具(開發者使用方法):圖1 - 人性化相對時間輸出

時間跨度的人性化

Humanizer 還可以使TimeSpan物件人性化,從而可以輕鬆地以易讀的格式顯示持續時間。

例如:人性化時間跨度

using System;

class TimeSpanHumanizerDemo
{
    static void Main()
    {
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        // Humanizing the TimeSpan into hours and minutes
        string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
        Console.WriteLine("Humanized TimeSpan: " + humanizedTimeSpan);
    }
}
using System;

class TimeSpanHumanizerDemo
{
    static void Main()
    {
        TimeSpan timeSpan = TimeSpan.FromMinutes(123);
        // Humanizing the TimeSpan into hours and minutes
        string humanizedTimeSpan = timeSpan.Humanize(2); // Output: "2 hours, 3 minutes"
        Console.WriteLine("Humanized TimeSpan: " + humanizedTimeSpan);
    }
}
$vbLabelText   $csharpLabel

! C# 人性化工具(開發者使用方法):圖 2 - 人性化 TimeSpan 輸出

數位運算

Humanizer 提供了多種方法,可以將數字轉換為人類可讀的詞語,並處理序數詞。

範例:將數字轉換為文字

using System;

class NumberHumanizerDemo
{
    static void Main()
    {
        int number = 123;
        // Convert number to words
        string words = number.ToWords(); // Output: "one hundred and twenty-three"
        Console.WriteLine("Number in Words: " + words);
    }
}
using System;

class NumberHumanizerDemo
{
    static void Main()
    {
        int number = 123;
        // Convert number to words
        string words = number.ToWords(); // Output: "one hundred and twenty-three"
        Console.WriteLine("Number in Words: " + words);
    }
}
$vbLabelText   $csharpLabel

! Humanizer C#(開發者使用方法):圖 3 - 數位轉文字輸出

範例:將數字轉換為序數

using System;

class OrdinalHumanizerDemo
{
    static void Main()
    {
        int number = 21;
        // Convert number to ordinal words
        string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
        Console.WriteLine("Ordinal Number: " + ordinal);
    }
}
using System;

class OrdinalHumanizerDemo
{
    static void Main()
    {
        int number = 21;
        // Convert number to ordinal words
        string ordinal = number.ToOrdinalWords(); // Output: "twenty-first"
        Console.WriteLine("Ordinal Number: " + ordinal);
    }
}
$vbLabelText   $csharpLabel

! Humanizer C#(開發者使用方法):圖 4 - 數字到序數的輸出

複數化和單數化

Humanizer 可以輕鬆地在單數和複數形式之間轉換單字,這對於根據數量動態產生長文字非常有用。

例如:單字的複數形式和單數形式

using System;

class PluralizationDemo
{
    static void Main()
    {
        string singular = "car";
        // Pluralize the word
        string plural = singular.Pluralize(); // Output: "cars"

        string word = "people";
        // Singularize the word
        string singularForm = word.Singularize(); // Output: "person"

        Console.WriteLine("Plural of 'car': " + plural);
        Console.WriteLine("Singular of 'people': " + singularForm);
    }
}
using System;

class PluralizationDemo
{
    static void Main()
    {
        string singular = "car";
        // Pluralize the word
        string plural = singular.Pluralize(); // Output: "cars"

        string word = "people";
        // Singularize the word
        string singularForm = word.Singularize(); // Output: "person"

        Console.WriteLine("Plural of 'car': " + plural);
        Console.WriteLine("Singular of 'people': " + singularForm);
    }
}
$vbLabelText   $csharpLabel

Humanizer 也能處理不規則的複數形式和單數形式,使其能很好地適應各種使用情境。

! Humanizer C#(開發者使用方法):圖 5 - 輸出複數化與單數化

枚舉格式化

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

例:枚舉的人性化

using System;

public enum MyEnum
{
    FirstValue,
    SecondValue
}

class EnumHumanizerDemo
{
    static void Main()
    {
        MyEnum enumValue = MyEnum.FirstValue;
        // Humanizing enum to a readable format
        string humanizedEnum = enumValue.Humanize(); // Output: "First value"

        Console.WriteLine("Humanized Enum: " + humanizedEnum);
    }
}
using System;

public enum MyEnum
{
    FirstValue,
    SecondValue
}

class EnumHumanizerDemo
{
    static void Main()
    {
        MyEnum enumValue = MyEnum.FirstValue;
        // Humanizing enum to a readable format
        string humanizedEnum = enumValue.Humanize(); // Output: "First value"

        Console.WriteLine("Humanized Enum: " + humanizedEnum);
    }
}
$vbLabelText   $csharpLabel

這種方法對於在使用者介面中顯示使用者友善的標籤尤其有用。

! C# 人性化(開發者使用方法):圖 6 - 人性化枚舉輸出

人性化位元組大小

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

例:使位元組大小更人性化

using System;

class ByteSizeHumanizerDemo
{
    static void Main()
    {
        long bytes = 1048576;
        // Humanize bytes to a readable size format
        string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"

        Console.WriteLine("Humanized Byte Size: " + humanizedBytes);
    }
}
using System;

class ByteSizeHumanizerDemo
{
    static void Main()
    {
        long bytes = 1048576;
        // Humanize bytes to a readable size format
        string humanizedBytes = bytes.Bytes().Humanize(); // Output: "1 MB"

        Console.WriteLine("Humanized Byte Size: " + humanizedBytes);
    }
}
$vbLabelText   $csharpLabel

! C# 人性化(開發者使用方法):圖 7 - 人性化位元組大小輸出

進階場景

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

範例:人性化日期時間偏移量

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

using System;

class DateTimeOffsetHumanizerDemo
{
    static void Main()
    {
        DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
        // Humanize DateTimeOffset
        string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"

        Console.WriteLine("Humanized DateTimeOffset: " + humanizedDateTimeOffset);
    }
}
using System;

class DateTimeOffsetHumanizerDemo
{
    static void Main()
    {
        DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddDays(-2);
        // Humanize DateTimeOffset
        string humanizedDateTimeOffset = dateTimeOffset.Humanize(); // Output: "2 days ago"

        Console.WriteLine("Humanized DateTimeOffset: " + humanizedDateTimeOffset);
    }
}
$vbLabelText   $csharpLabel

! C# 人性化(開發者使用方法):圖 8 - 人性化日期時間偏移輸出

性能考量

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 套件管理器

3.安裝 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 PDFGenerationDemo
{
    static void Main()
    {
        // Instantiate the PDF renderer
        var renderer = new ChromePdfRenderer();

        // Generate humanized content
        List<string> content = GenerateHumanizedContent();

        // HTML content template for the PDF
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Build the list items to add to the HTML content
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Render the HTML into a PDF document
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        pdf.SaveAs("output.pdf");

        Console.WriteLine("PDF document generated successfully: output.pdf");
    }

    /// <summary>
    /// Generates a list of humanized content examples
    /// </summary>
    /// <returns>List of humanized content as strings</returns>
    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 PDFGenerationDemo
{
    static void Main()
    {
        // Instantiate the PDF renderer
        var renderer = new ChromePdfRenderer();

        // Generate humanized content
        List<string> content = GenerateHumanizedContent();

        // HTML content template for the PDF
        string htmlContent = "<h1>Humanizer Examples</h1><ul>";

        // Build the list items to add to the HTML content
        foreach (var item in content)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Render the HTML into a PDF document
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        pdf.SaveAs("output.pdf");

        Console.WriteLine("PDF document generated successfully: output.pdf");
    }

    /// <summary>
    /// Generates a list of humanized content examples
    /// </summary>
    /// <returns>List of humanized content as strings</returns>
    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;
    }
}
$vbLabelText   $csharpLabel

Humanizer C#(開發者使用方法):圖 11 - PDF 輸出

結論

Humanizer 是一個不可或缺的程式庫,適用於旨在建立以使用者友好且易於理解的格式呈現資訊的應用程式的 .NET 開發人員。 它具有從日期和時間人性化到數位和枚舉格式等廣泛的功能,使其成為提高應用程式可用性的多功能工具。 透過利用 Humanizer,開發人員可以節省實現自訂格式化邏輯的時間和精力,確保他們的應用程式能夠更有效地向最終用戶傳達資料。

同樣,IronPDF 提供了全面的 PDF 生成和操作功能,使其成為在 C# 專案中建立和處理 PDF 文件的絕佳選擇。 Humanizer 和 IronPDF 結合使用,可顯著增強 .NET 應用程式的功能和呈現效果。 有關 IronPDF 許可的更多詳細信息,請參閱IronPDF 許可資訊。 如需了解更多信息,請查看我們的HTML 轉 PDF 詳細教程

常見問題解答

C# 中的 Humanizer 函式庫有什麼用途?

C# 中的 Humanizer 庫旨在將資料轉換為易於理解的格式,例如將日期轉換為相對時間字串、將單字轉換為複數形式、將數字格式化為單字以及處理枚舉類型。它可以幫助開發人員以更易讀、更易於存取的方式呈現資料。

如何在 C# 中將 DateTime 轉換為相對時間字串?

您可以使用 Humanizer 的Humanize方法將 DateTime 物件轉換為相對時間字串,例如「3 天前」或「5 小時後」。

如何在 C# 專案中安裝 Humanizer 程式庫?

若要在 C# 專案中安裝 Humanizer 函式庫,可以使用 NuGet 套件管理員控制台,指令為Install-Package Humanizer ,或使用 .NET Core CLI,指令為dotnet add package Humanizer

Humanizer可以進行哪些資料轉換?

Humanizer 可以執行多種資料轉換,例如將 Pascal 大小寫字串轉換為句子,將下劃線的字串轉換為標題大小寫,以及將長文字截斷為指定長度。

Humanizer 能否幫助 C# 實現單字的複數形式?

是的,Humanizer 提供了將單字複數化和單數化的方法,可以有效地處理規則和不規則形式,例如將“car”轉換為“cars”,或將“people”轉換為“person”。

Humanizer 如何在 C# 中處理枚舉?

Humanizer 可以將枚舉值轉換為人類可讀的字串,從而更容易在介面中顯示使用者友善的標籤。

C# PDF 庫提供哪些功能?

類似 IronPDF 的 AC# PDF 庫提供創建、讀取、編輯和提取 PDF 文件內容等功能。它還可以將 HTML 轉換為 PDF、合併文件以及添加浮水印。

如何在我的專案中安裝 C# PDF 庫?

若要安裝 C# PDF 庫,您可以使用 NuGet 套件管理器,在「瀏覽」標籤中搜尋庫名稱(例如 IronPDF),然後按一下「安裝」。

在 C# 中將 Humanizer 與 PDF 庫結合使用有哪些好處?

透過將 Humanizer 與 IronPDF 等 PDF 庫結合使用,開發人員可以使用 Humanizer 生成人類可讀的內容,然後將其渲染成 PDF 文檔,從而方便地創建用戶友好的 PDF 報告和文檔。

使用Humanizer時,我應該考慮哪些效能因素?

雖然 Humanizer 的設計目標是高效,但開發者應該考慮在需要高效能處理大型資料集或即時處理的應用程式中頻繁進行人性化操作的影響。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。