跳過到頁腳內容
.NET幫助

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

C# 提供了一個獨特的功能,可增強大型專案中代碼的組織與管理:局部關鍵字 class。 此功能可透過 partial 修改器存取,允許開發人員在多個檔案中分割類別、介面或結構的定義。 這項能力對於處理已產生的原始程式碼特別有利,例如使用者介面控制定義或服務封裝程式碼,以及客製化的業務邏輯。 在本文中,我們將學習使用 Visual Studio 的部分類別和 IronPDF PDF Library 適用於 .NET 的相關知識。

瞭解部分類別

在 C# 中,使用 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

使用部分方法。

部分類別也可以定義部分方法,這些方法已經宣告,但不一定會實作。 這些方法允許類別的一部分可以宣告一個方法而不實作它,選擇性地允許類的另一部分實作它。 如果未提供實作,則會在編譯時移除部分方法呼叫,因此不會造成效能損害。

// 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 關鍵字表示該方法可能有或可能沒有實作。

考慮一個 UI 元件需要在載入使用者介面控制之前執行某些動作的例子。 局部方法提供了一種乾淨的方式來插入自訂的商業邏輯,而不會使自動產生的程式碼變得雜亂無章。

// 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 classes 提供了一種無縫的方式,可將商業邏輯包含在獨立的原始碼檔案中,而不會改變自動產生的 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

部分類型的嵌套

Nested partial types 將部分類別的概念延伸到巢狀類別,允許在獨立的檔案中定義巢狀類的部分。 這對於組織大型巢狀結構特別有用,例如複雜的使用者介面控制定義,其中包含多個巢狀類型,用於處理控制行為的各個方面。

// 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

實際應用

部分類別對於涉及自動產生原始程式碼的情境特別有利,例如 Visual Studio 會建立 Windows Forms。 此設定可讓開發人員將 UI 設計代碼分開在不同的原始檔案中,使他們能夠在不影響原始 UI 設計的情況下,擴充或修改類別。

在 Web 應用程式中,部分類別有助於將生成的 Web 服務封裝程式碼與客製化業務邏輯分離,確保 Web 服務的更新不會覆蓋客製化修改。 同樣地,在使用 LINQ to SQL 的應用程式中,dbml 檔案會產生部分的類別定義,這些類別定義可以在不碰觸自動產生的程式碼的情況下進行擴充,以包含額外的功能或商業邏輯。

// 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 (How It Works For Developers):圖 1 - IronPDF

IronPDF 是適用於 .NET 的全面性函式庫,可讓開發人員在其應用程式中建立、讀取和編輯 PDF 文件。 它提供了一種直接的方法來使用 IronPDF、URL、圖像、ASPX 和文字從 HTML 生成 PDF,使其成為報告、文件生成和網頁內容歸檔的多功能工具。 IronPDF 的優點在於其易用性,只需最少的設定即可整合至任何 .NET 專案,包括使用 C# 開發的應用程式。

將 IronPDF 與部分類別整合。

為了說明 IronPDF 與部分類別的整合,讓我們考慮一個範例,我們有一個網頁應用程式,可以產生 PDF 格式的報表。 我們將在部分類別檔案中分割功能,以保持業務邏輯與 PDF 產生邏輯分離。

設定 IronPDF。

首先,確保 IronPDF 已加入您的專案。 通常可透過 NuGet Package Manager 使用下列指令完成:

Install-Package IronPdf

建立報告產生的部分類別

我們將課程分為兩部分:一部分是與報表資料相關的業務邏輯,另一部分是使用 IronPDF 產生 PDF。

檔案 1:報表產生器_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

用途

有了部分類別的設定,只要在 ReportGenerator 類的實體上呼叫 GeneratePdfReport 方法,就可以產生 PDF 報告。

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

C# Partial (How It Works For Developers):圖 2 - PDF 報告輸出

結論

C# Partial (How It Works For Developers):圖 3 - 授權

C# 中部分類別、部分方法和巢狀部分類型的使用,為開發人員提供了靈活且強大的程式碼組織與管理工具。 透過將自動產生的程式碼與商業邏輯、使用者介面控制定義以及應用程式的其他部分分離,開發人員可以建立更具維護性、可讀性與可擴充性的應用程式。

透過分開商業邏輯和 PDF 處理的關注點,開發人員可以達到更好的程式碼組織、可維護性和可擴展性。 IronPDF 的強大功能結合部分類別的組織優勢,為在專案中使用 PDF 的 .NET 開發人員創造了強大的工具集。 您可以使用其 免費試用 IronPDF 免費試用 IronPDF。 如果您有興趣購買,IronPDF 的許可證從 $999 開始。

常見問題解答

使用 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 创建和操作時。

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

局部類別對自動生成的代碼特别有用,因為它们允許開發者在不更改自動生成的部分的情况下添加自定义逻辑。這种分隔确保對生成代碼的任何更新都不会干扰自定义實現。

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 小時在線上。
聊天
電子郵件
打電話給我