跳過到頁腳內容
.NET幫助

Flunt C#(對於開發者的運行原理)

在目前的軟體開發環境中,製作高水準的文件並保證資料的完整性是不可或缺的任務。 在這篇文章中,我們將探討如何結合強大的 C# 函式庫、Flunt C# 和 IronPDF 來改善資料驗證和文件建立的工作流程。 開發人員可利用 IronPDF 精細的 PDF 製作功能和 Flunt 強大的驗證能力,為各種 軟體應用程式建構有效且可靠的解決方案。

How to use Flunt in C#

1.建立一個新的 C# 控制台專案。 2.從 NuGet 安裝 Flunt 套件。 3.導入命名空間並繼承類別。 4.將驗證加入資料模型。 5.執行驗證檢查並顯示結果。

Understanding of Flunt C#

多功能且輕量級的 .NET Framework Flunt 是為了促進 C# 應用程式中流暢驗證與通知模式的開發而建立的。 當開發人員使用 Flunt 以流暢且具表達力的方式建構驗證規則和商業邏輯時,程式碼會變得更容易閱讀和維護。 透過 Flunt 廣泛的整合驗證技術和擴充功能,開發人員可以輕鬆驗證物件和集合等複雜的資料結構。

此外,Flunt 是提升 .NET 程式庫應用程式可靠度與穩健性的有用工具,因為它可以輕鬆地與目前的程式碼庫和框架整合。 總而言之,Flunt 鼓勵使用宣告式的方法來驗證和處理錯誤,讓開發人員可以寫出更乾淨、更穩健的程式碼。

Features of Flunt C#

流暢的介面: Flunt 為建立驗證規則提供了清晰簡潔的介面,簡化了複雜驗證邏輯的表達。

Chainable Validation: 透過自然地連結驗證規則,只需少量程式碼即可建立 Chainable Validation 情境。

內建驗證器: Flunt 內建多種常用資料類型的驗證器,包括日期、整數、字串和集合。 流暢的語法可讓您輕鬆地將這些驗證器應用到屬性上。

自訂驗證規則:透過擴充 Flunt 框架,開發人員可以新增自訂驗證規則,讓驗證邏輯能符合特定領域的需求。

通知系統:為了報告驗證問題和收集錯誤訊息,Flunt 提供了一個通知系統。 這可讓開發人員簡單地通知使用者或其他應用程式元件驗證失敗。

與框架整合: Flunt 可輕鬆與知名的框架和函式庫 (包括 Entity Framework 和 ASP.NET Core) 連結,讓您輕鬆將驗證邏輯新增至已存在的專案。

可測性: Flunt 在應用程式程式碼與驗證邏輯之間進行了明確的區分,使單元測試驗證規則變得簡單,從而促進了測試驅動開發 (TDD)。

開放原始碼與蓬勃發展的社群:一群開發人員積極維護 Flunt,使其成為開放原始碼。 這樣才能保證持續維護、強化和支援該架構。

Getting Started with Flunt C#

在 C# 專案中設定 Flunt

Notifications 和 Validation 命名空間是 Flunt 基礎類庫的一部分,在您的 C# 專案中應該可以預設存取。 Flunt 透過提供定義和套用驗證規則的彈性介面,加速 C# 程式的驗證。 其支援更簡潔的程式碼、增強的可讀性和徹底的錯誤處理,使得驗證使用者輸入、網域物件和 API 請求變得更容易。

在 Windows Console 和 Forms 中實作 Flunt。

Flunt 由眾多 C# 應用程式類型實作,包括 Windows Console、Web 應用程式和 Windows Forms (WinForms)。 儘管每種架構都有不同的實作方式,但一般概念總是相同的。

Flunt C# (How It Works For Developers):圖 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 提供了許多操作,例如:

建立驗證規則:若要為強制欄位、資料類型、值範圍、最大長度和最小長度等屬性建立驗證規則,請使用 fluent 介面。

執行驗證:為了保證資料的完整性和對業務邏輯的遵循,根據預先定義的規則來驗證物件。

管理驗證錯誤:將驗證錯誤註記並記錄為警示,並透過給予使用者錯誤訊息或記錄錯誤以進行故障排除,禮貌地回應這些錯誤。

自訂驗證邏輯:使用獨特的驗證規則來擴充 Flunt,以因應複雜的驗證情況或特定領域的需求。

與框架整合:為了提高目前應用程式的驗證能力,Flunt 可以與許多知名的 .NET 框架和函式庫無縫整合,包括 Entity Framework、ASP.NET Core 等。

將 Flunt 與 IronPDF 整合。

開發人員可以利用這兩種技術的優勢,透過整合 Flunt 與 IronPDF,加速 C# 應用程式中的商業邏輯驗證及文件建立。 開發人員可使用 IronPDF 在使用 Flunt 驗證輸入資料後建立 PDF 文件,使應用程式更可靠、更易於使用。

安裝 IronPDF。

  • 啟動 Visual Studio 專案。
  • 選擇"工具">"NuGet Package Manager">"Package Manager Console"。
  • 在套件管理員控制台輸入此指令:
Install-Package IronPdf
  • 作為替代方案,您可以使用 NuGet Package Manager for Solutions 安裝 IronPDF 和其他必要的 NuGet 套件。
  • 探索並從搜尋結果中選擇 IronPDF 套件後,按一下"安裝"按鈕。 安裝與下載將由 Visual Studio 處理。

!Flunt C# (How It Works For Developers):圖 2 - 使用管理 NuGet Package for Solution 安裝 IronPDF,方法是在 NuGet Package Manager 的搜尋列中搜尋 "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.Main 方法:使用範例 Person 資料,我們在 Main 方法中建立一個 User 類別的實體。 接下來,我們使用 Flunt 的 IsValid 屬性來確定 Person 資料是否合法。 為了建立 PDF 文件,如果資料正確,我們會調用 IronPDF 方法。 否則會在控制台顯示驗證問題。

透過結合 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# (How It Works For Developers):圖 3 - 上述程式碼利用 Flunt 與 IronPDF 的輸出範例

結論

IronPDF 和 Flunt 是兩個強大的 C# 函式庫,兩者搭配使用可簡化文件建立和資料驗證的工作流程。 有了 IronPDF 精細的 PDF 製作功能和 Flunt 強大的驗證能力,開發人員可以為各種應用程式建構可靠、有效且高水準的解決方案。 Flunt 和 IronPDF 為開發人員提供了必要的工具,讓他們無論是開發桌面應用程式、網頁應用程式或雲端解決方案,都能創造出符合使用者和利害關係人需求的高品質軟體。

$999 Lite 套裝包含一年的軟體支援、永久許可證和庫升級。 IronPDF 提供 免費的 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# 是開源的,由開發者社群維護。這使其成為開源項目的一個可靠選擇,提供持續的更新和支持。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我