.NET 幫助

流暢的 C#(它對開發者的運作原理)

發佈 2024年6月6日
分享:

介紹

在當前的軟體開發環境中,產出高品質的文件和保證數據完整性是必不可少的任務。在這篇文章中,我們將探討如何結合強大的C#庫,Flunt C#和IronPDF,以改進數據驗證和文件創建的工作流程。開發人員可以為多種需求構建高效且可靠的解決方案。 應用程式 利用IronPDF的先進PDF製作功能和Fluent的強大驗證能力。

如何在 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 促進了測試驅動開發。 (測試驅動開發) 通過在應用程式代碼和驗證邏輯之間提供明確的劃分,使其易於單元測試驗證規則。

開源和繁榮的社群:一群開發人員積極維護 Flunt,使其保持開源狀態。這保證了框架的持續維護、增強和支持。

入門 Flunt C

在C#項目中設定Flunt

Notifications和Validation命名空間是Flunt基礎類庫的一部分,應該在您的C#項目中默認可用。Flunt通過提供一個靈活的介面來定義和應用驗證規則,加速了C#程序的驗證。它對更清晰的代碼、更高的可讀性和全面的錯誤處理的支持,使驗證用戶輸入、域對象和API請求更加容易。

在 Windows 控制台和表單中實現 Flunt

Flunt 被眾多 C# 應用類型所實現,包括 Windows 控制台、網頁應用程式和 Windows Forms (WinForms)雖然每個框架有不同的實現方式,但一般的概念總是相同的。

Flunt C#(對開發者的運作方式):圖1 - 使用Visual Studio軟件包管理器搜索Flunt並安裝

Flunt C#範例

您可以在安裝 Flunt 後立即使用以下代碼。這是一個簡單的範例,顯示了如何使用 Flunt 構建驗證規則:

using Flunt.Validations;
static void Main(string[] args)
{
    var person = new Person { Name = "Jack", Age = -25 };
    var contract = new PersonContract(person);
    // 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 Flunt.Validations;
static void Main(string[] args)
{
    var person = new Person { Name = "Jack", Age = -25 };
    var contract = new PersonContract(person);
    // 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 Flunt.Validations
Shared Sub Main(ByVal args() As String)
	Dim person As New Person With {
		.Name = "Jack",
		.Age = -25
	}
	Dim contract = New PersonContract(person)
	' 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
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
VB   C#

Person 類別:FluentValidation 的範例相同。

PersonContract: 這個類別源自 Flunt 的基本概念 Contract.Verifications。透過 Requires 方法,建構子接受一個 Person 對象並提供驗證規則。Requires 提供了一種可鏈接的方法來添加多種驗證。驗證是由像 IsNotNullNotEmptyHasMinLengthIsGreaterThan 這類方法來進行的。每個驗證規則都可以有個性化的錯誤訊息。

驗證: 可比擬 FluentValidation 的範例。與對象一起,它創建一個 PersonContract 實例和一個 Person 對象。驗證結果透過合同的 Valid 屬性顯示。根據驗證結果,會顯示成功或失敗的通知以及特定的錯誤詳情。

流暢操作

在 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包為解決方案安裝IronPDF,方法是在NuGet包管理器的搜索欄中搜索「IronPdf」,然後選擇項目並點擊安裝按鈕。

  • 安裝 IronPDF 套件和您專案所需的任何相依套件將由 NuGet 處理。
  • 安裝完成後,IronPDF 可在您的專案中使用。

通過 NuGet 網站安裝

要了解有關 IronPDF 的功能、兼容性和其他下載選擇的更多信息,請參閱其在 NuGet 網站上的頁面 https://www.nuget.org/packages/IronPdf

利用 DLL 安裝

作為替代方案,您可以利用 IronPDF 的 DLL 檔案直接將其包含到您的專案中。要獲取包含 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數據,我們在主方法中構建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 sb = new StringBuilder();
            var person = new Person { Name = "Jack", Age = -25 };
            var contract = new PersonContract(person);
            if (contract.IsValid)
            {
                Console.WriteLine("Person is valid!");
            }
            else
            {
                sb.Append("<p>Validation failed: </p>");
                foreach (var notification in contract.Notifications)
                {
                    sb.Append($"- {notification.Key}: {notification.Message}");
                }
            }
            var renderer = new IronPdf.HtmlToPdf();
            //Set HTML content for the page
            var pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString());
            // save the document
            pdfDocument.SaveAs("output.pdf");
            //Dispose the render 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 sb = new StringBuilder();
            var person = new Person { Name = "Jack", Age = -25 };
            var contract = new PersonContract(person);
            if (contract.IsValid)
            {
                Console.WriteLine("Person is valid!");
            }
            else
            {
                sb.Append("<p>Validation failed: </p>");
                foreach (var notification in contract.Notifications)
                {
                    sb.Append($"- {notification.Key}: {notification.Message}");
                }
            }
            var renderer = new IronPdf.HtmlToPdf();
            //Set HTML content for the page
            var pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString());
            // save the document
            pdfDocument.SaveAs("output.pdf");
            //Dispose the render 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)
			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!")
			Else
				sb.Append("<p>Validation failed: </p>")
				For Each notification In contract.Notifications
					sb.Append($"- {notification.Key}: {notification.Message}")
				Next notification
			End If
			Dim renderer = New IronPdf.HtmlToPdf()
			'Set HTML content for the page
			Dim pdfDocument = renderer.RenderHtmlAsPdf(sb.ToString())
			' save the document
			pdfDocument.SaveAs("output.pdf")
			'Dispose the render 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
VB   C#

以下是上述程式碼的執行輸出:

Flunt C#(對開發者的作用):圖 3 - 上述代碼使用 Fluent 和 IronPDF 的示例輸出

結論

IronPDF 和 Flunt 是兩個強大的 C# 資料庫,它們可以很好地協同工作,以精簡文件創建和數據驗證的工作流程。憑藉 IronPDF 的先進 PDF 生成功能和 Flunt 的強大驗證能力,開發人員可以為各種應用構建可靠、高效且高水準的解決方案。無論是開發桌面應用、網絡應用還是基於雲端的解決方案,Flunt 和 IronPDF 都為開發人員提供了創建符合用戶和利益相關者需求的高質量軟件所需的工具。

Lite 捆綁包包括一年的軟件支持、永久許可和資料庫升級。IronPDF 提供 免費授權 請參閱IronPDF了解有關成本和許可要求的更多詳情。如需更多有關Iron Software庫的資訊,請訪問此 網站。

< 上一頁
Nswag C# (開發人員如何使用)
下一個 >
docfx C#(它如何運作給開發者)

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

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