跳過到頁腳內容
.NET幫助

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

C# 提供了一個獨特的特性,可以提高大型項目中代碼的組織和管理:partial 關鍵字類。 這個特性可以通過 partial 修飾符來訪問,允許開發者將類、介面或結構的定義分散到多個文件中。 這個功能對於使用已生成的源代碼(例如用戶介面控件定義或服務包裝代碼)以及自定義業務邏輯非常有利。 在本文中,我們將了解 partial 類以及使用 Visual Studio 的 IronPDF PDF Library for .NET

理解 Partial 類

在 C# 中,一個 partial 類(保持相同的訪問級別)是使用 partial 修飾符定義的,表示類的定義分散在同一程序集中的兩個或多個文件中。 這種方法將相關代碼保持在一起,同時保持關注點分離。 例如,一個 partial 類 Employee 的業務邏輯可能在一個文件中,而數據訪問層在另一個文件中,但這兩部分都被編譯成一個類。 這種分離不僅使代碼更易於管理,還允許多個開發人員在沒有衝突的情況下對同一類進行工作。

// File 1: Employee_BusinessLogic.cs
public partial class Employee
{
    // Method for calculating pay
    public void CalculatePay() 
    { 
        // Implementation of pay calculation
    }
}

// File 2: Employee_DataAccess.cs
public partial class Employee
{
    // Method for loading employee data
    public void Load() 
    { 
        // Implementation of data loading
    }
}
// File 1: Employee_BusinessLogic.cs
public partial class Employee
{
    // Method for calculating pay
    public void CalculatePay() 
    { 
        // Implementation of pay calculation
    }
}

// File 2: Employee_DataAccess.cs
public partial class Employee
{
    // Method for loading employee data
    public void Load() 
    { 
        // Implementation of data loading
    }
}
' File 1: Employee_BusinessLogic.cs
Partial Public Class Employee
	' Method for calculating pay
	Public Sub CalculatePay()
		' Implementation of pay calculation
	End Sub
End Class

' File 2: Employee_DataAccess.cs
Partial Public Class Employee
	' Method for loading employee data
	Public Sub Load()
		' Implementation of data loading
	End Sub
End Class
$vbLabelText   $csharpLabel

利用 Partial 方法

Partial 類還可以定義 partial 方法,這些方法是聲明而不一定實現的。 這些方法允許在類的一部分中聲明一個方法而不實現它,並可選擇允許類的另一部分實現它。 如果沒有提供實現,則在編譯時會刪除 partial 方法調用,不會造成性能損失。

// File 1: Employee_BusinessLogic.cs
public partial class Employee
{
    // Declaration of a partial method to be called when pay is calculated
    partial void OnPayCalculated(double amount);

    public void CalculatePay()
    {
        double amount = 1000; // Simplified calculation
        OnPayCalculated(amount); // Call the partial method
    }
}

// File 2: Employee_Events.cs
public partial class Employee
{
    // Implementation of the partial method
    partial void OnPayCalculated(double amount)
    {
        Console.WriteLine($"Pay calculated: {amount}");
    }
}
// File 1: Employee_BusinessLogic.cs
public partial class Employee
{
    // Declaration of a partial method to be called when pay is calculated
    partial void OnPayCalculated(double amount);

    public void CalculatePay()
    {
        double amount = 1000; // Simplified calculation
        OnPayCalculated(amount); // Call the partial method
    }
}

// File 2: Employee_Events.cs
public partial class Employee
{
    // Implementation of the partial method
    partial void OnPayCalculated(double amount)
    {
        Console.WriteLine($"Pay calculated: {amount}");
    }
}
' File 1: Employee_BusinessLogic.cs
Partial Public Class Employee
	' Declaration of a partial method to be called when pay is calculated
	Partial Private Sub OnPayCalculated(ByVal amount As Double)
	End Sub

	Public Sub CalculatePay()
		Dim amount As Double = 1000 ' Simplified calculation
		OnPayCalculated(amount) ' Call the partial method
	End Sub
End Class

' File 2: Employee_Events.cs
Partial Public Class Employee
	' Implementation of the partial method
	Private Sub OnPayCalculated(ByVal amount As Double)
		Console.WriteLine($"Pay calculated: {amount}")
	End Sub
End Class
$vbLabelText   $csharpLabel

高級使用部分方法

Partial 方法體現了一種部分定義的方法,允許在 partial 類的一部分中聲明而在另一部分中可選擇實現。 這個特性對於在生成的代碼中提供鉤子可以由開發人員可選擇地實現特別有用。 partial 關鍵字表示該方法可能有也可能沒有實現。

想像一個例子,其中一個 UI 組件需要在用戶界面控件加載之前執行某些操作。 Partial 方法提供了一種清晰的方式插入自定義業務邏輯而不混淆自動生成的代碼。

// File: UIControls_AutoGenerated.cs
public partial class UIControls
{
    // Declaration of a partial method for control loading
    partial void OnControlLoading();

    public void LoadControl()
    {
        OnControlLoading(); // Call the partial method
        // Auto-generated loading logic here
    }
}

// File: UIControls_CustomLogic.cs
public partial class UIControls
{
    // Implementation of the partial method for adding custom logic
    partial void OnControlLoading()
    {
        // Custom business logic code here
        Console.WriteLine("Custom control loading logic executed.");
    }
}
// File: UIControls_AutoGenerated.cs
public partial class UIControls
{
    // Declaration of a partial method for control loading
    partial void OnControlLoading();

    public void LoadControl()
    {
        OnControlLoading(); // Call the partial method
        // Auto-generated loading logic here
    }
}

// File: UIControls_CustomLogic.cs
public partial class UIControls
{
    // Implementation of the partial method for adding custom logic
    partial void OnControlLoading()
    {
        // Custom business logic code here
        Console.WriteLine("Custom control loading logic executed.");
    }
}
' File: UIControls_AutoGenerated.cs
Partial Public Class UIControls
	' Declaration of a partial method for control loading
	Partial Private Sub OnControlLoading()
	End Sub

	Public Sub LoadControl()
		OnControlLoading() ' Call the partial method
		' Auto-generated loading logic here
	End Sub
End Class

' File: UIControls_CustomLogic.cs
Partial Public Class UIControls
	' Implementation of the partial method for adding custom logic
	Private Sub OnControlLoading()
		' Custom business logic code here
		Console.WriteLine("Custom control loading logic executed.")
	End Sub
End Class
$vbLabelText   $csharpLabel

將業務邏輯與 Partial 類集成

業務邏輯通常需要超出自動生成內容的修改和擴展,尤其是在具有複雜規則或行為的應用程序中。 Partial 類提供了一種無縫的方式在不更改自動生成的 UI 或數據訪問代碼的情況下在單獨的源文件中包含業務邏輯。 這種分離確保了業務邏輯易於訪問和修改,增強了合作,尤其是在多個開發人員同時進行項目工作時。

// File: Employee_AutoGenerated.cs
public partial class Employee
{
    // Auto-generated properties and methods
}

// File: Employee_BusinessLogic.cs
public partial class Employee
{
    // Business logic method for promoting an employee
    public void Promote()
    {
        // Business logic code to promote an employee
        Console.WriteLine("Employee promoted.");
    }
}
// File: Employee_AutoGenerated.cs
public partial class Employee
{
    // Auto-generated properties and methods
}

// File: Employee_BusinessLogic.cs
public partial class Employee
{
    // Business logic method for promoting an employee
    public void Promote()
    {
        // Business logic code to promote an employee
        Console.WriteLine("Employee promoted.");
    }
}
' File: Employee_AutoGenerated.cs
Partial Public Class Employee
	' Auto-generated properties and methods
End Class

' File: Employee_BusinessLogic.cs
Partial Public Class Employee
	' Business logic method for promoting an employee
	Public Sub Promote()
		' Business logic code to promote an employee
		Console.WriteLine("Employee promoted.")
	End Sub
End Class
$vbLabelText   $csharpLabel

嵌套部分類型

嵌套部分類型將部分類的概念擴展到嵌套類,允許嵌套類的部分定義在不同的文件中。 這對於組織大型嵌套結構特別有用,例如一個複雜的用戶界面控件定義,它包括多個嵌套類型來處理控件行為的各個方面。

// File: ComplexControl_Part1.cs
public partial class ComplexControl
{
    public partial class NestedControl
    {
        // Method for initializing the nested control
        public void Initialize() 
        { 
            // Initialization code here 
        }
    }
}

// File: ComplexControl_Part2.cs
public partial class ComplexControl
{
    public partial class NestedControl
    {
        // Method for cleaning up the nested control
        public void Cleanup() 
        { 
            // Cleanup code here 
        }
    }
}
// File: ComplexControl_Part1.cs
public partial class ComplexControl
{
    public partial class NestedControl
    {
        // Method for initializing the nested control
        public void Initialize() 
        { 
            // Initialization code here 
        }
    }
}

// File: ComplexControl_Part2.cs
public partial class ComplexControl
{
    public partial class NestedControl
    {
        // Method for cleaning up the nested control
        public void Cleanup() 
        { 
            // Cleanup code here 
        }
    }
}
' File: ComplexControl_Part1.cs
Partial Public Class ComplexControl
	Partial Public Class NestedControl
		' Method for initializing the nested control
		Public Sub Initialize()
			' Initialization code here 
		End Sub
	End Class
End Class

' File: ComplexControl_Part2.cs
Partial Public Class ComplexControl
	Partial Public Class NestedControl
		' Method for cleaning up the nested control
		Public Sub Cleanup()
			' Cleanup code here 
		End Sub
	End Class
End Class
$vbLabelText   $csharpLabel

實際應用

Partial 類在涉及自動生成的源代碼的情境中特別有利,例如 Windows Forms,其中 Visual Studio 創建 Windows Forms。 這種設置允許開發人員將 UI 設計代碼分離到一個獨立的源文件中,這樣他們就可以在不影響原始 UI 設計的情況下擴展或修改類。

在 Web 應用程序中,Partial 類促進了生成的 Web 服務包裝代碼與自定義業務邏輯的分離,確保 Web 服務的更新不會覆蓋自定義修改。 同樣地,在使用 LINQ to SQL 的應用程序中,dbml 文件生成的 partial 類定義可以擴展,以包括附加功能或業務邏輯而不更改自動生成的代碼。

// Auto-generated UI class
public partial class MainForm : Form
{
    // Designer code
}

// Custom logic for MainForm
public partial class MainForm
{
    // Custom event handlers and methods
}
// Auto-generated UI class
public partial class MainForm : Form
{
    // Designer code
}

// Custom logic for MainForm
public partial class MainForm
{
    // Custom event handlers and methods
}
' Auto-generated UI class
Partial Public Class MainForm
	Inherits Form

	' Designer code
End Class

' Custom logic for MainForm
Partial Public Class MainForm
	Inherits Form

	' Custom event handlers and methods
End Class
$vbLabelText   $csharpLabel

IronPDF:C# PDF 庫

C# Partial(開發者如何使用):圖 1 - IronPDF

IronPDF 是一個全面的 .NET 庫,允許開發人員在他們的應用程序中創建、閱讀和編輯 PDF 文件。 它提供了一種簡單的方法從 HTML 生成 PDF 使用 IronPDF,包括 URL、圖像、ASPX 和文本,使其成為報告、文件生成和 Web 內容存檔的多功能工具。 IronPDF 在易用性方面表現出色,只需進行最少的設置即可集成到任何 .NET 項目中,包括 C# 開發的應用程序。

將 IronPDF 與 Partial 類集成

為了說明 IronPDF 與 Partial 類的集成,我們來考慮一個我們有一個生成報告 PDF 格式的 Web 應用程序的例子。 我們將功能劃分到 Partial 類文件中,以將業務邏輯與 PDF 生成邏輯分開。

設置 IronPDF

首先,確保 IronPDF 被添加到你的項目中。 這通常可以通過 NuGet 包管理器使用命令來完成:

Install-Package IronPdf

為報告生成創建 Partial 類

我們將把類分成兩部分:一部分用於與報告數據相關的業務邏輯,另一部分用於使用 IronPDF 生成 PDF。

文件 1:ReportGenerator_BusinessLogic.cs

該文件包含準備報告數據的業務邏輯。

public partial class ReportGenerator
{
    // Method to get data for the report
    public IEnumerable<string> GetDataForReport()
    {
        // Imagine this method fetches and prepares data for the report
        return new List<string> { "Data1", "Data2", "Data3" };
    }
}
public partial class ReportGenerator
{
    // Method to get data for the report
    public IEnumerable<string> GetDataForReport()
    {
        // Imagine this method fetches and prepares data for the report
        return new List<string> { "Data1", "Data2", "Data3" };
    }
}
Partial Public Class ReportGenerator
	' Method to get data for the report
	Public Function GetDataForReport() As IEnumerable(Of String)
		' Imagine this method fetches and prepares data for the report
		Return New List(Of String) From {"Data1", "Data2", "Data3"}
	End Function
End Class
$vbLabelText   $csharpLabel

文件 2:ReportGenerator_PdfGeneration.cs

該文件利用 IronPDF 從準備好的數據生成 PDF 報告。

public partial class ReportGenerator
{
    // Method to generate PDF report using IronPDF
    public void GeneratePdfReport()
    {
        var renderer = new IronPdf.ChromePdfRenderer();
        var data = GetDataForReport();
        var htmlContent = $"<html><body><h1>Report</h1><p>{string.Join("</p><p>", data)}</p></body></html>";

        // Generate PDF from HTML string
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        pdf.SaveAs("Report.pdf");
        Console.WriteLine("Report generated successfully.");
    }
}
public partial class ReportGenerator
{
    // Method to generate PDF report using IronPDF
    public void GeneratePdfReport()
    {
        var renderer = new IronPdf.ChromePdfRenderer();
        var data = GetDataForReport();
        var htmlContent = $"<html><body><h1>Report</h1><p>{string.Join("</p><p>", data)}</p></body></html>";

        // Generate PDF from HTML string
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        pdf.SaveAs("Report.pdf");
        Console.WriteLine("Report generated successfully.");
    }
}
Partial Public Class ReportGenerator
	' Method to generate PDF report using IronPDF
	Public Sub GeneratePdfReport()
		Dim renderer = New IronPdf.ChromePdfRenderer()
		Dim data = GetDataForReport()
		Dim htmlContent = $"<html><body><h1>Report</h1><p>{String.Join("</p><p>", data)}</p></body></html>"

		' Generate PDF from HTML string
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF to a file
		pdf.SaveAs("Report.pdf")
		Console.WriteLine("Report generated successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

用法

使用 Partial 類設置,生成 PDF 報告就像在 ReportGenerator 類的實例上調用 GeneratePdfReport 方法一樣簡單。

var reportGenerator = new ReportGenerator();
reportGenerator.GeneratePdfReport();
var reportGenerator = new ReportGenerator();
reportGenerator.GeneratePdfReport();
Dim reportGenerator As New ReportGenerator()
reportGenerator.GeneratePdfReport()
$vbLabelText   $csharpLabel

C# Partial(開發者如何使用):圖 2 - PDF 報告輸出

結論

C# Partial(開發者如何使用):圖 3 - 授權

在 C# 中使用 Partial 類、Partial 方法和嵌套部分類型為開發人員提供了一種靈活而強大的工具來進行代碼組織和管理。 通過將自動生成的代碼與業務邏輯、用戶界面控件定義和應用程序的其他部分分開,開發人員可以創建更易於維護、可讀和可伸縮的應用程序。

通過將業務邏輯和 PDF 處理分離,開發人員可以實現更好的代碼組織、維護性和可擴展性。 IronPDF 的強大功能結合 Partial 類的組織優勢,為使用 PDF 的 .NET 開發人員創造了一個強大的工具集。 您可以通過其IronPDF 免費試用。 如果您有購買意願,IronPDF 的許可證起價為 $799。

常見問題解答

使用 C# 局部類別的目的是什么?

C# 中的局部類別用於將一個類別、接口或結構的定义拆分到多個文件中。這對於將自動生成的代碼(如 UI 控件)與自定義業務邏輯分離特別有用,從而增強代碼管理和組織性。

在網絡應用程序中,局部類別有哪些好處?

在網絡應用程序中,局部類別允許開發人員將 UI 設計代碼與自定義業務邏輯分開。這種分離有助于保持清晰的代碼架構,從而更容易管理和擴展隨著應用程序的增長。

C# 中 partial 關鍵字的重要性是什么?

C# 中的 partial 關鍵字表示類別、接口或結構的定义分為不同文件中的幾个部分。這個特性對於管理大型代碼庫特別重要,尤其是在處理自動生成的代碼時。

您能否在 C# 中使用局部類別集成 PDF 生成功能?

是的,您可以在 C# 中使用局部類別集成 PDF 生成功能。通过使用像 IronPDF 这样的库,可以将 PDF 生成邏輯分离到一个局部類別中,与其他业务逻辑区分开,增强代码清晰度。

局部方法在局部類別中如何工作?

局部類別中的局部方法在類別的一个部分中声明而无实现,并且可以在另一部分中选择性地实现。如果局部方法被声明但未实现,它将在编译时被移除,从而避免性能负担。

什么是嵌套局部类型,它们的用途是什么?

嵌套局部类型允许嵌套类的一部分在不同文件中定义。這種組織工具對於管理复杂結構很有用,例如具有多个嵌套类型的用户界面控件,从而实现更好的代码管理。

.NET PDF 功能库如何安装?

像 IronPDF 这样的 .NET PDF 功能库可以通过 NuGet 包管理器安装。您可以使用特定于包的命令,例如:Install-Package IronPdf

使用局部類別进行协作开发有哪些优点?

局部類別有助于协作开发,允许多个开发人员在不发生代码冲突的情况下在同一类的不同部分上工作。這是通過將類別拆分成多个文件來实现的,从而更容易管理并发修改。

如何在 C# 项目中组织生成 PDF 的逻辑?

在 C# 项目中可以使用局部類別将 PDF 生成逻辑与其他业务逻辑分开,从而提高代碼的可管理性和清晰度,特别是在使用 IronPDF 这样的库进行 PDF 创建和操作时。

局部類別对自動生成的代碼有何用?

局部類別对自動生成的代碼特别有用,因为它们允许开发者在不更改自動生成的部分的情况下添加自定义逻辑。這种分隔确保对生成代码的任何更新都不会干扰自定义实现。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。