.NET 幫助

流暢的 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 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
$vbLabelText   $csharpLabel

Person 類別:FluentValidation 範例中的相同。

PersonContract此類別源自 Flunt 的基本概念Contract.Verifications。 使用 Requires 方法,構造函數接受一個 Person 對象並提供驗證規則。 Requires提供了一種可鏈式調用的方法,用於添加多個驗證。 驗證由像是IsNotNullNotEmptyHasMinLengthIsGreaterThan的方法來執行。 每個驗證規則都有個性化的錯誤訊息可供使用。

驗證:類似於 FluentValidation.Together 與該對象的示例,創建了 PersonContract 實例和 Person 對象。 驗證結果由合約的 Valid 屬性顯示。 根據驗證結果,將顯示成功或失敗的通知以及特定錯誤詳情。

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 套件管理器的搜尋欄位中搜尋 IronPdf,使用管理 NuGet 套件為解決方案安裝 IronPDF,然後選擇專案並點擊安裝按鈕。

  • 安裝IronPDF套件以及專案所需的任何相依性都將由NuGet處理。
  • 安裝後,IronPDF 可供您在項目中使用。

通過NuGet網站安裝

若要了解有關 IronPDF 的功能、相容性及其他下載選擇,請參閱其在 NuGet 網站上的NuGet 套件詳細資訊頁面

利用 DLL 進行安裝

作為替代方案,您可以使用 IronPDF 的 DLL 檔案直接將其包含在您的專案中。 要獲取包含 DLL 的 ZIP 文件,請訪問以下IronPDF ZIP 下載頁面。 將 DLL 解壓縮後,將其包含到您的專案中。

實現邏輯

讓我們創建一個基本的 C# 應用程式,使用 IronPDF 進行 PDF 創建以及 Flunt 進行數據驗證。 在此範例中,我們將使用 Flunt 驗證註冊表單的使用者輸入,並使用 IronPDF 創建包含已驗證使用者資料摘要的 PDF 文件。

  1. Person 類別: 定義了一個具有姓名和年齡屬性的 Person 類別。 我們在構造函數中使用Flunt的流暢界面,根據預定義的驗證規則驗證Person數據。

  2. 生成 PDF:定義了一個名為RenderHtmlAsPdf的方法,並接受一個 User 物件作為輸入。 此功能使用 IronPDF 的HtmlToPdf類別將用戶註冊摘要的 HTML 文本呈現為 PDF 文檔。

  3. 主要方法:使用範例人員數據,我們在主要方法中構建一個 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
$vbLabelText   $csharpLabel

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

Flunt C#(適用於開發人員的運作方式):圖3 - 結果範例展示了如何同時使用Fluent和IronPDF

結論

IronPDF 和 Flunt 是兩個強大的 C# 函式庫,它們結合得很好,可以簡化文檔創建和數據驗證的工作流程。 借助IronPDF的先進PDF製作功能和Flunt的強大驗證能力,開發人員可以為各種應用構建可靠、高效和高品質的解決方案。 Flunt 和 IronPDF 為開發人員提供必要的工具,以創建滿足用戶和利益相關者需求的高品質軟體,無論是開發桌面應用程式、網絡應用程式還是基於雲的解決方案。

一年的软件支持、永久授权和库升级都包含在$749 Lite 套装中。 IronPDF 提供 免費授權詳細資訊,以獲取有關成本和授權要求的進一步資訊。 如需有關 Iron Software 程式庫的更多資訊,請造訪 Iron Software 官方網站。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Nswag C# (開發人員如何使用)
下一個 >
docfx C#(它如何運作給開發者)