跳至页脚内容
.NET 帮助

Flunt C#(开发人员如何使用)

在当前的软件开发环境中,制作高质量文档和保证数据完整性是至关重要的任务。 在这篇文章中,我们将探讨如何结合强大的C#库,Flunt C#和IronPDF,以改进数据验证和文档创建的工作流程。 开发人员可以通过利用IronPDF的复杂PDF生产功能和Flunt的强大验证能力来构建适用于多种软件应用程序的有效和可靠的解决方案。

如何在C#中使用Flunt

  1. 创建一个新的C#控制台项目。
  2. 从NuGet安装Flunt包。
  3. 导入命名空间并继承类。
  4. 将验证添加到数据模型。
  5. 执行验证检查并显示结果。

理解Flunt C

多功能且轻量级的.NET框架Flunt是为方便在C#应用程序中开发流利的验证和通知模式而创建的。 当开发人员使用Flunt以流畅和富有表现力的方式来构建验证规则和业务逻辑时,代码变得更易读和维护。 利用Flunt广泛的内置验证技术和扩展方法,开发人员可以轻松验证复杂的数据结构,例如对象和集合。

此外,Flunt易于集成到当前的代码库和框架中,是提高.NET库应用程序的可靠性和稳健性的有用工具。 总的来说,Flunt鼓励以声明方式进行验证和错误处理,使开发人员能够编写更简洁、更健壮的代码。

Flunt C#的功能

流畅接口: Flunt提供了一个易读和简洁的接口来构建验证规则,简化复杂验证逻辑的表达。

可链接验证: 通过自然连接验证规则,可以用少量代码创建可链接的验证场景。

集成的验证器: Flunt带有几个内置的验证器,用于常用的数据类型,包括日期、整数、字符串和集合。 流畅的语法允许轻松地将这些验证器应用于属性。

自定义验证规则: 通过扩展Flunt框架,开发人员可以添加自定义验证规则,使验证逻辑适应特定领域需求。

通知系统: Flunt提供了一个通知系统,用于报告验证问题并收集错误信息。 这使得开发人员可以轻松地通知用户或其他应用程序组件验证失败。

集成框架: Flunt轻松连接到包括Entity Framework和ASP.NET Core在内的知名框架和库,使得将验证逻辑添加到现有项目变得简单。

可测试性: Flunt通过在应用程序代码和验证逻辑之间提供明确的划分,促进了测试驱动开发(TDD),使得单元测试验证规则变得简单。

开源和活跃社区: Flunt是由一组开发人员积极维护的开源项目。 这保证了框架的持续维护、改进和支持。

开始使用Flunt C

在C#项目中设置Flunt

通知和验证命名空间是Flunt基类库的一部分,默认情况下应该可以在您的C#项目中访问。 Flunt通过提供一个灵活的接口来定义和应用验证规则,加速C#程序的验证。 其对更干净的代码、增强的可读性和全面错误处理的支持,使验证用户输入、域对象和API请求变得更加容易。

在Windows控制台和表单中实现Flunt

Flunt由许多C#应用程序类型实现,包括Windows控制台、Web应用程序和Windows Forms(WinForms)。 尽管每个框架有不同的实现,但总体概念始终保持不变。

Flunt C# (如何为开发人员工作):图1 - 使用Visual Studio包管理器搜索Flunt并安装它

Flunt C#示例

您可以在安装完成后立即使用下面的Flunt代码。 这是一个简单的例子,展示了如何使用Flunt构建验证规则:

using System;
using Flunt.Validations;

public class Program
{
    static void Main(string[] args)
    {
        var person = new Person { Name = "Jack", Age = -25 };
        var contract = new PersonContract(person);

        // Perform validation checks
        if (contract.IsValid)
        {
            Console.WriteLine("Person is valid!");
        }
        else
        {
            Console.WriteLine("Validation failed:");
            foreach (var notification in contract.Notifications)
            {
                Console.WriteLine($"- {notification.Key}: {notification.Message}");
            }
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class PersonContract : Contract<Person>
{
    public PersonContract(Person person)
    {
        // Ensure the correct format of the object
        Requires()
            .IsNotNull(person, nameof(person))
            .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
            .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
    }
}
using System;
using Flunt.Validations;

public class Program
{
    static void Main(string[] args)
    {
        var person = new Person { Name = "Jack", Age = -25 };
        var contract = new PersonContract(person);

        // Perform validation checks
        if (contract.IsValid)
        {
            Console.WriteLine("Person is valid!");
        }
        else
        {
            Console.WriteLine("Validation failed:");
            foreach (var notification in contract.Notifications)
            {
                Console.WriteLine($"- {notification.Key}: {notification.Message}");
            }
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class PersonContract : Contract<Person>
{
    public PersonContract(Person person)
    {
        // Ensure the correct format of the object
        Requires()
            .IsNotNull(person, nameof(person))
            .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
            .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
    }
}
Imports System
Imports Flunt.Validations

Public Class Program
	Shared Sub Main(ByVal args() As String)
		Dim person As New Person With {
			.Name = "Jack",
			.Age = -25
		}
		Dim contract = New PersonContract(person)

		' Perform validation checks
		If contract.IsValid Then
			Console.WriteLine("Person is valid!")
		Else
			Console.WriteLine("Validation failed:")
			For Each notification In contract.Notifications
				Console.WriteLine($"- {notification.Key}: {notification.Message}")
			Next notification
		End If
	End Sub
End Class

Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class

Public Class PersonContract
	Inherits Contract(Of Person)

	Public Sub New(ByVal person As Person)
		' Ensure the correct format of the object
		Requires().IsNotNull(person, NameOf(person)).IsNotEmpty(person.Name, NameOf(person.Name), "Name is required").IsGreaterThan(person.Age, 0, NameOf(person.Age), "Age must be a positive number")
	End Sub
End Class
$vbLabelText   $csharpLabel

Person类: 表示具有NameAge属性的实体。

PersonContract 该类源自Flunt的基本概念Contract<T>。 使用Requires方法,构造函数接收一个Person对象并提供验证规则。 Requires提供了一个可链接的方法,用于定义多个验证。 通过如IsNotNullIsNotEmptyIsGreaterThan等方法进行验证。 每个验证规则都有相关的自定义错误消息。

验证: 类似于一个FluentValidation示例,创建一个PersonContract和一个Person对象的实例。 验证结果由合同的IsValid属性显示。 根据验证结果会显示成功或失败通知以及具体的错误消息。

Flunt操作

对于C#应用程序中验证和通知处理,Flunt提供了许多操作,例如:

创建验证规则: 使用流畅的接口来为诸如必填字段、数据类型、值范围、最大长度和最小长度等属性创建验证规则。

执行验证: 使对象根据预定义的规则进行验证,以确保数据完整性和符合业务逻辑。

管理验证错误: 将验证错误记录并作为警报响应,通过向用户提供错误消息或记录错误进行故障排除。

自定义验证逻辑: 在应对复杂验证场景或特定领域需求时,使用独特的验证规则来扩展Flunt。

集成框架: Flunt可以无缝集成到许多著名的.NET框架和库中,包括Entity Framework、ASP.NET Core等,以增强现有应用程序的验证能力。

将Flunt与IronPDF集成

通过将Flunt与IronPDF集成,开发人员可以利用这两种技术的优势,加速C#应用程序中的业务逻辑验证和文档创建。 通过在使用Flunt验证输入数据后使用IronPDF创建PDF文档,开发人员可以使应用程序更加可靠和用户友好。

安装 IronPDF。

  • 启动Visual Studio项目。
  • 选择“工具”>“NuGet包管理器”>“包管理器控制台”。
  • 在包管理器控制台输入此命令:
Install-Package IronPdf
  • 或者,您可以使用解决方案的NuGet包管理器来安装IronPDF和其他必要的NuGet包。
  • 在搜索结果中浏览并选择IronPDF包后点击“安装”按钮。 由Visual Studio处理安装和下载。

Flunt C# (如何为开发人员工作):图2 - 使用NuGet包管理器的解决方案,通过在NuGet包管理器的搜索栏中搜索“IronPdf”,然后选择项目并点击安装按钮,安装IronPDF。

  • NuGet将处理安装IronPDF包以及您的项目所需的任何依赖项。
  • 安装后,IronPDF可以在您的项目中使用。

通过NuGet网站安装

要了解更多关于IronPDF的功能、兼容性和其他下载选项,请参见其NuGet包详细信息页面

使用DLL安装

或者,您也可以利用IronPDF的DLL文件将其直接包含到您的项目中。 访问以下IronPDF ZIP下载页面以获取包含DLL的ZIP文件。 DLL解压后将其包含在您的项目中。

实施逻辑

让我们创建一个基本的C#应用程序,使用IronPDF进行PDF创建,使用Flunt进行数据验证。 在此示例中,我们将使用Flunt验证用户输入的注册表单,并使用IronPDF创建具有已验证用户数据摘要的PDF文档。

  1. Person类: 定义一个具有姓名和年龄属性的Person类。 通过在构造函数中使用Flunt的流畅接口,我们根据预定义的验证规则验证Person数据。
  2. 生成Pdf: 定义名为RenderHtmlAsPdf的方法,它接受一个User对象作为输入。 此函数通过使用IronPDF的HtmlToPdf类将表示用户注册摘要的HTML文本呈现为PDF文档。
  3. 主方法: 使用示例Person数据,在Main方法中构建一个User类的实例。 接下来,我们使用Flunt的IsValid属性来确定Person数据是否合法。 如果数据正确,则调用IronPdf方法创建PDF文档。 如果不正确,则在控制台显示验证问题。

通过结合IronPDF进行PDF生成和Flunt进行数据验证,我们在C#应用程序中开发了一种快速工作流程,用于评估用户输入和生成PDF文档。 此方法确保数据的完整性,生成专业质量的文档,并鼓励编写清晰、可读和可维护的代码。 要了解更多关于IronPDF的功能,请参考文档页面。 下面是示例代码片段。

using IronPdf;
using System;
using System.Linq;
using System.Text;
using Flunt.Validations;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // StringBuilder for HTML content
            StringBuilder sb = new StringBuilder();
            var person = new Person { Name = "Jack", Age = -25 };
            var contract = new PersonContract(person);

            if (contract.IsValid)
            {
                Console.WriteLine("Person is valid!");
                sb.Append("<p>Person is valid!</p>");
            }
            else
            {
                sb.Append("<p>Validation failed: </p>");
                foreach (var notification in contract.Notifications)
                {
                    sb.Append($"- {notification.Key}: {notification.Message}<br>");
                }
            }

            var renderer = new HtmlToPdf();
            // Set HTML content for the page
            var pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString());
            // Save the document
            pdfDocument.SaveAs("output.pdf");
            // Dispose the renderer object
            renderer.Dispose();
            // Display a message
            Console.WriteLine("Report generated successfully!");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class PersonContract : Contract<Person>
    {
        public PersonContract(Person person)
        {
            Requires()
                .IsNotNull(person, nameof(person))
                .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
                .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
        }
    }
}
using IronPdf;
using System;
using System.Linq;
using System.Text;
using Flunt.Validations;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // StringBuilder for HTML content
            StringBuilder sb = new StringBuilder();
            var person = new Person { Name = "Jack", Age = -25 };
            var contract = new PersonContract(person);

            if (contract.IsValid)
            {
                Console.WriteLine("Person is valid!");
                sb.Append("<p>Person is valid!</p>");
            }
            else
            {
                sb.Append("<p>Validation failed: </p>");
                foreach (var notification in contract.Notifications)
                {
                    sb.Append($"- {notification.Key}: {notification.Message}<br>");
                }
            }

            var renderer = new HtmlToPdf();
            // Set HTML content for the page
            var pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString());
            // Save the document
            pdfDocument.SaveAs("output.pdf");
            // Dispose the renderer object
            renderer.Dispose();
            // Display a message
            Console.WriteLine("Report generated successfully!");
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class PersonContract : Contract<Person>
    {
        public PersonContract(Person person)
        {
            Requires()
                .IsNotNull(person, nameof(person))
                .IsNotEmpty(person.Name, nameof(person.Name), "Name is required")
                .IsGreaterThan(person.Age, 0, nameof(person.Age), "Age must be a positive number");
        }
    }
}
Imports IronPdf
Imports System
Imports System.Linq
Imports System.Text
Imports Flunt.Validations

Namespace ConsoleApp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' StringBuilder for HTML content
			Dim sb As New StringBuilder()
			Dim person As New Person With {
				.Name = "Jack",
				.Age = -25
			}
			Dim contract = New PersonContract(person)

			If contract.IsValid Then
				Console.WriteLine("Person is valid!")
				sb.Append("<p>Person is valid!</p>")
			Else
				sb.Append("<p>Validation failed: </p>")
				For Each notification In contract.Notifications
					sb.Append($"- {notification.Key}: {notification.Message}<br>")
				Next notification
			End If

			Dim renderer = New HtmlToPdf()
			' Set HTML content for the page
			Dim pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString())
			' Save the document
			pdfDocument.SaveAs("output.pdf")
			' Dispose the renderer object
			renderer.Dispose()
			' Display a message
			Console.WriteLine("Report generated successfully!")
		End Sub
	End Class

	Public Class Person
		Public Property Name() As String
		Public Property Age() As Integer
	End Class

	Public Class PersonContract
		Inherits Contract(Of Person)

		Public Sub New(ByVal person As Person)
			Requires().IsNotNull(person, NameOf(person)).IsNotEmpty(person.Name, NameOf(person.Name), "Name is required").IsGreaterThan(person.Age, 0, NameOf(person.Age), "Age must be a positive number")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

下面是上面代码的执行输出:

Flunt C# (如何为开发人员工作):图3 - 使用以上代码利用Flunt和IronPDF的示例输出

结论

IronPDF和Flunt是两个强大的C#库,能够很好地协同工作以简化文档创建和数据验证的工作流。 借助IronPDF的高级PDF生产功能和Flunt的强大验证能力,开发人员可以为各种应用程序构建可靠、高效和高质量的解决方案。 无论是在开发桌面应用程序、Web应用程序还是基于云的解决方案,Flunt和IronPDF都为开发人员提供了创建满足用户和利益相关方需求的高质量软件所需的工具。

$799 Lite捆绑包包括一年的软件支持、永久许可证和图书馆升级。 IronPDF为获取更多关于成本和许可证要求的详细信息提供免费许可证详情。 有关Iron Software库的更多信息,请访问<Iron Software官方网站>。

常见问题解答

Flunt C# 如何改善我应用程序中的验证过程?

Flunt C# 提供了一个流式接口,增强了验证过程,使开发人员可以以一种可读和易于维护的方式创建复杂的验证规则。它支持可链式验证场景,并且与如 ASP.NET Core 和 Entity Framework 这样的框架无缝集成。

设置 Flunt C# 进行验证涉及哪些步骤?

要设置 Flunt C# 进行验证,需要创建一个新的 C# 项目,从 NuGet 安装 Flunt 包,导入必要的命名空间,并继承基类以构建验证规则和逻辑。

IronPDF 如何与 Flunt C# 集成以增强文档创建?

IronPDF 可以与 Flunt C# 一起使用,在生成 PDF 之前验证输入数据。这确保了只有有效的数据被使用,从而提高生成文档的可靠性。在验证之后,IronPDF 允许您以编程方式创建专业质量的 PDF 文档。

使用 Flunt C# 进行测试驱动开发的好处是什么?

Flunt C# 支持测试驱动开发,使验证逻辑和应用代码明确分离。这种分离允许开发人员轻松地编写和运行验证规则的单元测试,确保应用程序的正确性和稳健性。

Flunt C# 能处理自定义验证规则吗?

可以,Flunt C# 允许开发人员定义自定义验证规则,以满足特定的应用需求。这种灵活性有助于处理内置验证器无法覆盖的独特验证场景。

在 C# 项目中安装 IronPDF 的过程是什么?

要安装 IronPDF,请打开您的 Visual Studio 项目,导航到 '工具' > 'NuGet 包管理器' > '包管理器控制台',然后执行命令 Install-Package IronPdf。或者,您可以使用 NuGet 包管理器来为解决方案添加 IronPDF 到您的项目中。

Flunt C# 中的通知系统起什么作用?

Flunt C# 中的通知系统设计用于捕获和报告验证错误。它允许开发人员收集错误消息和反馈,可用于通知用户或应用程序的其他组件关于验证问题的信息。

Flunt C# 适合用于开源项目吗?

是的,Flunt C# 是开源的,由开发者社区维护。这使其成为开源项目的可靠选择,提供持续的更新和支持。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。