Humanizer C#(對於開發者的運行原理)
Humanizer 是一個強大且靈活的 .NET 程式庫,它簡化並人性化了處理資料的過程,特別是在以使用者友好的格式顯示資訊時。 無論您需要將日期轉換為相對時間字串("3天前")、將單詞複數化、將數字格式化為單詞,或處理枚舉、顯示字串、Pascal 案例輸入字串為帶有自定義描述的句子、下劃線輸入字串轉換為普通標題案例字串和長文字截斷,Humanizer 提供了大量工具和擴展方法,以優雅地在 C#.NET 中處理這些任務,將非人性化的輸入字串轉換為句子。
在這篇文章中,我們將討論 Humanizer 在 C# 中的詳細教程。 我們還將討論如何使用 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;
Imports Humanizer
人性化日期和時間
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);
}
}
Imports System
Friend Class HumanizerDemo
Shared Sub Main()
Dim pastDate As DateTime = DateTime.Now.AddDays(-3)
' Humanize the past date, which converts it to a relative time format
Dim humanizedTime As String = pastDate.Humanize() ' Output: "3 days ago"
Dim futureDate As DateTime = DateTime.Now.AddHours(5)
' Humanize the future date, presenting it in relative time
Dim futureHumanizedTime As String = futureDate.Humanize() ' Output: "in 5 hours"
Console.WriteLine("Humanized Past Date: " & humanizedTime)
Console.WriteLine("Humanized Future Date: " & futureHumanizedTime)
End Sub
End Class
Humanizer 擴展方法自動處理不同的時間單位,甚至進行語法正確的調整。

人性化 TimeSpans
Humanizer 也可以人性化 TimeSpan 物件,使其易於以可讀格式顯示持續時間。
範例:人性化 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);
}
}
Imports System
Friend Class TimeSpanHumanizerDemo
Shared Sub Main()
Dim timeSpan As TimeSpan = System.TimeSpan.FromMinutes(123)
' Humanizing the TimeSpan into hours and minutes
Dim humanizedTimeSpan As String = timeSpan.Humanize(2) ' Output: "2 hours, 3 minutes"
Console.WriteLine("Humanized TimeSpan: " & humanizedTimeSpan)
End Sub
End Class

處理數字
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);
}
}
Imports System
Friend Class NumberHumanizerDemo
Shared Sub Main()
Dim number As Integer = 123
' Convert number to words
Dim words As String = number.ToWords() ' Output: "one hundred and twenty-three"
Console.WriteLine("Number in Words: " & words)
End Sub
End Class

範例:將數字轉換為序數
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);
}
}
Imports System
Friend Class OrdinalHumanizerDemo
Shared Sub Main()
Dim number As Integer = 21
' Convert number to ordinal words
Dim ordinal As String = number.ToOrdinalWords() ' Output: "twenty-first"
Console.WriteLine("Ordinal Number: " & ordinal)
End Sub
End Class

複數化與單數化
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);
}
}
Imports System
Friend Class PluralizationDemo
Shared Sub Main()
Dim singular As String = "car"
' Pluralize the word
Dim plural As String = singular.Pluralize() ' Output: "cars"
Dim word As String = "people"
' Singularize the word
Dim singularForm As String = word.Singularize() ' Output: "person"
Console.WriteLine("Plural of 'car': " & plural)
Console.WriteLine("Singular of 'people': " & singularForm)
End Sub
End Class
Humanizer 也處理不規則的複數化和單數化,使其對於各種用例都十分強大。

格式化枚舉
枚舉在 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);
}
}
Imports System
Public Enum MyEnum
FirstValue
SecondValue
End Enum
Friend Class EnumHumanizerDemo
Shared Sub Main()
Dim enumValue As MyEnum = MyEnum.FirstValue
' Humanizing enum to a readable format
Dim humanizedEnum As String = enumValue.Humanize() ' Output: "First value"
Console.WriteLine("Humanized Enum: " & humanizedEnum)
End Sub
End Class
此方法對於在使用者介面中顯示使用者友好的標籤特別有用。

人性化字節大小
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);
}
}
Imports System
Friend Class ByteSizeHumanizerDemo
Shared Sub Main()
Dim bytes As Long = 1048576
' Humanize bytes to a readable size format
Dim humanizedBytes As String = bytes.Bytes().Humanize() ' Output: "1 MB"
Console.WriteLine("Humanized Byte Size: " & humanizedBytes)
End Sub
End Class

進階範例
Humanizer 不僅限於上述的基本範例。 它支持廣泛的進階功能,例如 Truncate 方法和多種語言與擴展。
範例:人性化 DateTime 偏移量
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);
}
}
Imports System
Friend Class DateTimeOffsetHumanizerDemo
Shared Sub Main()
Dim dateTimeOffset As DateTimeOffset = System.DateTimeOffset.Now.AddDays(-2)
' Humanize DateTimeOffset
Dim humanizedDateTimeOffset As String = dateTimeOffset.Humanize() ' Output: "2 days ago"
Console.WriteLine("Humanized DateTimeOffset: " & humanizedDateTimeOffset)
End Sub
End Class

效能考量
Humanizer 設計為高效,但像任何程式庫一樣,其效能依賴於如何使用。 對於需要高效能的應用程式,尤其是處理大型資料集或實時處理的應用程式,考慮到頻繁的人性化操作的影響是至關重要的。
IronPDF for C
IronPDF 是一個針對 .NET 應用開發的全面 PDF 生成和操作程式庫。 它讓開發者能夠輕鬆地建立、閱讀、編輯和從 PDF 文件中提取内容。 IronPDF 設計為使用者友好,提供了一系列廣泛的功能,包括將 HTML 轉換為 PDF、合併文件、新增水印等。 其多功能性和強大特性使其成為在 C# 專案中處理 PDF 文件的絕佳選擇。
透過 NuGet 套件管理器安裝 IronPDF
按照以下步驟透過 NuGet 套件管理器安裝 IronPDF:
-
打開您的 Visual Studio 專案:
- 啟動 Visual Studio 並打開現有的 C# 專案或建立一個新的。
-
打開 NuGet 套件管理器:
- 在方案總管中右鍵點擊您的專案。
- 從上下文選單中選擇"管理 NuGet 套件..."。

-
安裝 IronPDF:
- 在 NuGet 套件管理器中,轉到"瀏覽"標籤。
- 查找 IronPDF。
- 從搜索結果中選擇 IronPDF 套件。
- 點擊"安裝"按鈕將 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;
}
}
Imports Humanizer
Imports IronPdf
Imports System
Imports System.Collections.Generic
Friend Class PDFGenerationDemo
Shared Sub Main()
' Instantiate the PDF renderer
Dim renderer = New ChromePdfRenderer()
' Generate humanized content
Dim content As List(Of String) = GenerateHumanizedContent()
' HTML content template for the PDF
Dim htmlContent As String = "<h1>Humanizer Examples</h1><ul>"
' Build the list items to add to the HTML content
For Each item In content
htmlContent &= $"<li>{item}</li>"
Next item
htmlContent &= "</ul>"
' Render the HTML into a PDF document
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF to a file
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF document generated successfully: output.pdf")
End Sub
''' <summary>
''' Generates a list of humanized content examples
''' </summary>
''' <returns>List of humanized content as strings</returns>
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

結論
Humanizer 是一個對於 .NET 開發者想要建立以使用者友好和人性化格式呈現資訊之應用程式時不可或缺的程式庫。 其廣泛的功能,例如日期和時間人性化到數字和枚舉格式化,令其成為提高應用程式可用性的重要工具。 藉由利用 Humanizer,開發者可以在實施自定格式化邏輯上省時省力,確保應用程式能更有效地向終端使用者傳達資料。
類似地,IronPDF 提供了全面的 PDF 生成和操作能力,成為在 C# 專案中建立和處理 PDF 文件的絕佳選擇。 Humanizer 和 IronPDF 合作,能顯著增強 .NET 應用的功能和呈現。 有關 IronPDF 授權的更多詳細資訊,請參閱 IronPDF 授權資訊。 要進一步探索,請查看我們的 HTML 轉 PDF 詳細教程。
常見問題
Humanizer程式庫在C#中的目的為何?
C#中的Humanizer程式庫旨在將資料轉換為人性化格式,例如將日期轉換為相對時間字串、將單字複數化、將數字格式化為單字,以及處理列舉。幫助開發者以更易讀的方式呈現資料。
如何在C#中將DateTime轉換為相對時間字串?
您可以使用Humanizer的Humanize方法將DateTime物件轉換為相對時間字串,例如「3天前」或「5小時後」。
如何在C#專案中安裝Humanizer程式庫?
要在C#專案中安裝Humanizer程式庫,您可以在NuGet Package Manager Console中使用命令Install-Package Humanizer或使用.NET Core CLI的dotnet add package Humanizer。
使用Humanizer可以進行哪些資料轉換的範例?
Humanizer可以進行多種資料轉換,比如將Pascal case字串轉換為句子,將底線字串轉換為標題大小寫,並將長文字截斷到指定長度。
Humanizer可以幫助C#中的單字複數化嗎?
是的,Humanizer提供方法來複數化和單數化單字,有效處理規則和不規則形式,例如將「car」轉換為「cars」或將「people」轉換為「person」。
Humanizer如何在C#中處理列舉?
Humanizer可以將列舉值轉換為人性化字串,使顯示使用者友好的標籤在介面中變得更加容易。
C# PDF程式庫提供了哪些功能?
類似IronPDF的C# PDF程式庫提供建立、讀取、編輯和從PDF文件中提取內容等功能。同時也可以將HTML轉換為PDF、合併文件和新增浮水印。
如何在我的專案中安裝C# PDF程式庫?
要安裝C# PDF程式庫,您可以使用NuGet Package Manager在「瀏覽」標籤中搜索程式庫名稱,如IronPDF,然後點擊「安裝」。
將Humanizer和PDF程式庫結合在C#中有哪些好處?
透過將Humanizer與像IronPDF的PDF程式庫結合使用,開發者可以生成由Humanizer人性化的內容,然後將其呈現為PDF文件,從而方便建立使用者友好的PDF報告和文件。
使用Humanizer時需要考慮哪些性能因素?
雖然Humanizer設計為高效,開發者仍需考慮在需要高效能的應用程式中,對大型資料集或實時處理進行頻繁的人性化操作時的影響。




