.NET 帮助

Humanizer C#(它是如何为开发人员工作的)

发布 2024年七月1日
分享:

Humanizer 是一个强大而灵活的 .NET 库,可简化数据处理过程并使之人性化,尤其是在以用户友好的格式显示信息方面。无论您需要将日期转换为相对时间字符串 ("3天前")Humanizer提供了大量的工具和扩展方法,可在C#.NET中优雅地处理这些任务,将非人性化的输入字符串转换为句子。

在本文中,我们将讨论 C# 中 Humanizer 的详细教程。我们还将讨论如何使用 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 最常见的用途之一是使用 "人性化 "方法将日期和时间转换为人类可读的格式、时间跨度、数字和数量。这对于显示相对时间特别有用,例如 "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 - 人性化时间跨度输出

使用数字

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 可以将枚举值转换为人类可读的字符串。

示例:人性化枚举

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#

这种方法对于在用户界面中显示方便用户的标签特别有用。

Humanizer C#(如何为开发人员工作):图 6 - 人性化枚举输出

人性化的字节大小

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 并不局限于上述基本场景。它支持多种高级功能,如 "截断 "方法以及多种语言和扩展功能。

示例:人性化日期时间偏移

Humanizer 还可以处理 "日期时间偏移",这对处理时区的应用程序非常有用。

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 - 日期时间偏移输出人性化

性能考虑因素

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.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >