跳過到頁腳內容
.NET幫助

C# 主建構函數(開發者的工作原理)

在 C# 程式設計的物件導向領域中,Primary Constructors 的導入為語言的優雅與簡潔帶來了新的境界。 主建構器與截取器和集合表達式等功能一起,在 C# 12 中以強大的功能出現,提供更簡潔的語法來宣告帶有參數的建構器。 您可以在 Microsoft C# 指南 上深入探索 Primary 結構器。

在這篇文章中,我們將學習如何有效率地使用 C# 12 主構成器,也會探討它們的功能、使用案例,以及它們如何改變開發人員處理類初始化的方式。

基礎知識:C# 中的建構函式

構建器在物件導向程式設計中扮演關鍵的角色,是物件初始化的藍圖。 傳統上,C# 開發人員會使用預設的建構器或參數化的建構器來設定其類別的初始狀態。 然而,Primary Constructors 的引入為 C# 開發的這一重要方面增添了更精簡的方法。

主要構成式的精髓

C# 中的 Primary Constructor 是在類別宣告中直接宣告和初始化屬性的簡潔方式。 它簡化了為屬性定義和賦值的過 程,提供了更具宣告性和可讀性的語法。

主要構成程式的優點

1.簡潔性:主要的建構程式提供簡潔的語法,減少模板程式碼並提高可讀性。 2.範圍:與傳統的構造子不同,主要構造子中的參數在整個類別或結構體中都屬於範圍,因此使用上具有彈性。 3.預設值:預設參數值簡化了物件的建立,使開發人員更為方便。

宣告主要構成式

Primary Constructor 的語法包括直接在類別標頭中宣告屬性。 讓我們來看一個基本的 Person 類別範例:

public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
    public override string ToString() => $"Name: {Name}, Age: {Age}";
}
public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
    public override string ToString() => $"Name: {Name}, Age: {Age}";
}
Public Class Person(String name, Integer age)
	Public ReadOnly Property Name() As String = name
	Public ReadOnly Property Age() As Integer = age
	Public Overrides Function ToString() As String
		Return $"Name: {Name}, Age: {Age}"
	End Function
End Class
$vbLabelText   $csharpLabel

在上述程式碼片段中,Person 類別有一個 Primary Constructor,可初始化實體成員 Name 和實體成員 Age 的屬性。 構建器參數會與類別或結構名稱一起宣告,在定義公開屬性時,會將參數值指定給它們。

範例 1:2D 空間中的不可變點

public readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}
public readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}
'INSTANT VB WARNING: VB has no equivalent to the C# readonly struct:
'ORIGINAL LINE: public readonly struct Point(double x, double y)
Public Structure Point(Double x, Double y)
	Public ReadOnly Property X() As Double = x
	Public ReadOnly Property Y() As Double = y
	Public ReadOnly Property Magnitude() As Double
		Get
			Return Math.Sqrt(X * X + Y * Y)
		End Get
	End Property
End Structure
$vbLabelText   $csharpLabel

在這個範例中,Point 結構的主要建構器會初始化 XY 兩個屬性,展現了語法的簡潔性和表達力。

範例 2:具有預設設定的可設定記錄器

public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
{
    private readonly string _filePath = filePath;
    private readonly LogLevel _level = level;

    public void Log(string message)
    {
        // Actual logging implementation using _filePath and _level
    }
}
public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
{
    private readonly string _filePath = filePath;
    private readonly LogLevel _level = level;

    public void Log(string message)
    {
        // Actual logging implementation using _filePath and _level
    }
}
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
Public Class Logger(String filePath = "log.txt", LogLevel level = LogLevel.Info)
	Private ReadOnly _filePath As String = filePath
	Private ReadOnly _level As LogLevel = level

	Public Sub Log(ByVal message As String)
		' Actual logging implementation using _filePath and _level
	End Sub
End Class
$vbLabelText   $csharpLabel

在此,Logger 類的主要建構器為 filePathlevel 提供預設值,使其在保持可配置性的同時,更靈活易用。

範例 3:依賴注入

public interface IService
{
    Distance GetDistance();
}

public class ExampleController(IService service) : ControllerBase
{
    public ActionResult<Distance> Get() => service.GetDistance();
}
public interface IService
{
    Distance GetDistance();
}

public class ExampleController(IService service) : ControllerBase
{
    public ActionResult<Distance> Get() => service.GetDistance();
}
Public Interface IService
	Function GetDistance() As Distance
End Interface

Public Class ExampleController(IService service)
	Inherits ControllerBase

	Public Function [Get]() As ActionResult(Of Distance)
		Return service.GetDistance()
	End Function
End Class
$vbLabelText   $csharpLabel

主要的建構程式適合依賴注入的情境。 在這個範例中,一個控制器類別指出了它的依賴關係,增強了可維護性並促進了單元測試。

範例 4:建立幾何圖形層次結構

public abstract class Shape(double width, double height)
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public abstract double CalculateArea();
}

public class Rectangle(double width, double height) : Shape(width, height)
{
    public override double CalculateArea() => Width * Height;
}

public class Circle : Shape
{
    public Circle(double radius) : base(radius * 2, radius * 2) { }
    public override double CalculateArea() => Math.PI * Math.Pow(Width / 2, 2);
}
public abstract class Shape(double width, double height)
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public abstract double CalculateArea();
}

public class Rectangle(double width, double height) : Shape(width, height)
{
    public override double CalculateArea() => Width * Height;
}

public class Circle : Shape
{
    public Circle(double radius) : base(radius * 2, radius * 2) { }
    public override double CalculateArea() => Math.PI * Math.Pow(Width / 2, 2);
}
Public MustInherit Class Shape(Double width, Double height)
	Public ReadOnly Property Width() As Double = width
	Public ReadOnly Property Height() As Double = height
	Public MustOverride Function CalculateArea() As Double
End Class

Public Class Rectangle(Double width, Double height)
	Inherits Shape(width, height)

	Public Overrides Function CalculateArea() As Double
		Return Width * Height
	End Function
End Class

Public Class Circle
	Inherits Shape

	Public Sub New(ByVal radius As Double)
		MyBase.New(radius * 2, radius * 2)
	End Sub
	Public Overrides Function CalculateArea() As Double
		Return Math.PI * Math.Pow(Width / 2, 2)
	End Function
End Class
$vbLabelText   $csharpLabel

在這個範例中,Shape 類中的主要建構器構成了幾何形狀階層結構的基礎。 子類如 RectangleCircle 會利用主要建構器來進行一致的初始化。 Rectangle 類本身會宣告主要的建構子,並將擷取的主要建構子參數傳送給 Shape 類的主要參數。 Circle 類別透過在整個類別中定義其建構器來展現其靈活性,然後再使用 base 關鍵字將其參數傳給 Shape 建構器作為預設值。

介紹 IronPDF。

IronPDF 是一個多功能的 C# 函式庫,可讓開發人員毫不費力地建立、處理和轉換 PDF 檔案。 無論您是要產生發票、報告或任何其他文件,IronPDF 都能讓您直接在 C# 應用程式中,將 HTML 內容無縫轉換為精緻且專業的 PDF。

IronPDF 是開發人員的便利工具,可讓他們將網頁、URL 和 HTML 轉換成 PDF。 最棒的是 PDF 檔案看起來就像原始網頁一樣,所有格式和樣式都會保留。 它非常適合從報告和發票等網頁內容建立 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Primary Constructor (How It Works For Developer):圖 1 - IronPDF 網頁

安裝 IronPDF:快速入門

若要將 IronPDF 納入您的 C# 專案,請先安裝 IronPDF NuGet 套件。 在套件管理員控制台執行下列指令:

Install-Package IronPdf

或者,在 NuGet Package Manager 中找到 "IronPDF",並從那裡進行安裝。

C# Primary Constructor (How It Works For Developer):圖 2 - 在 NuGet 套件管理員瀏覽器中搜尋 IronPDF 套件

使用 IronPDF 生成 PDF。

使用 IronPDF 創建 PDF 是一個簡化的流程。 請考慮以下範例:

var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf");
var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf");
Dim htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>"
' Create a new PDF document
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf")
$vbLabelText   $csharpLabel

在這個範例中,IronPDF 被用來將 HTML 內容渲染成 PDF 文件,並隨後儲存到指定的位置。 有關在 C# 中建立和操作 PDF 的詳細資訊,請造訪這個完整的 教學連結,若要探索更多,請造訪這個 文件說明頁面。

C# Primary Constructors:類初始化的革命

C# Primary Constructors 提供了一種宣告式且精簡的方法,可直接在類別宣告中初始化類別屬性。 讓我們來探討這個優雅的功能是否能與 IronPDF 無縫整合。

將 C# 主要構成程式與 IronPDF 整合。

雖然 C# 主要構建器主要是一種專注於類別初始化的語言功能,但其與 IronPDF 的直接整合可能不是常見的使用案例。 IronPDF 的核心功能在於 PDF 文件的產生和處理,而類初始化的具體細節可能與此工作流程不直接相符。

然而,開發人員在定義與 IronPDF 配置或資料模型相關的自訂類別或結構時,可以利用 C# Primary Constructors。 舉例來說,如果您的應用程式需要特定的類別結構來管理 PDF 相關的設定或組態,C# Primary Constructors 可以成為簡潔初始化這些類別的重要工具。

public class PdfGenerationSettings(string title, bool includeHeader, bool includeFooter)
{
    public string Title { get; } = title;
    public bool IncludeHeader { get; } = includeHeader;
    public bool IncludeFooter { get; } = includeFooter;
    // Additional properties...
}

// Usage with IronPDF
var pdfSettings = new PdfGenerationSettings("My PDF Title", true, false);
var renderOptions = new ChromePdfRenderOptions
{
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    Title = pdfSettings.Title
};
// Apply settings from PdfGenerationSettings
if (pdfSettings.IncludeHeader)
{
    renderOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
}
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderingOptions = renderOptions;
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf");
public class PdfGenerationSettings(string title, bool includeHeader, bool includeFooter)
{
    public string Title { get; } = title;
    public bool IncludeHeader { get; } = includeHeader;
    public bool IncludeFooter { get; } = includeFooter;
    // Additional properties...
}

// Usage with IronPDF
var pdfSettings = new PdfGenerationSettings("My PDF Title", true, false);
var renderOptions = new ChromePdfRenderOptions
{
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    Title = pdfSettings.Title
};
// Apply settings from PdfGenerationSettings
if (pdfSettings.IncludeHeader)
{
    renderOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
}
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderingOptions = renderOptions;
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf");
Public Class PdfGenerationSettings(String title, Boolean includeHeader, Boolean includeFooter)
	Public ReadOnly Property Title() As String = title
	Public ReadOnly Property IncludeHeader() As Boolean = includeHeader
	Public ReadOnly Property IncludeFooter() As Boolean = includeFooter
	' Additional properties...
End Class

' Usage with IronPDF
Private pdfSettings = New PdfGenerationSettings("My PDF Title", True, False)
Private renderOptions = New ChromePdfRenderOptions With {
	.PaperSize = IronPdf.Rendering.PdfPaperSize.A4,
	.MarginTop = 20,
	.MarginBottom = 20,
	.MarginLeft = 10,
	.MarginRight = 10,
	.Title = pdfSettings.Title
}
' Apply settings from PdfGenerationSettings
If pdfSettings.IncludeHeader Then
	renderOptions.TextHeader = New TextHeaderFooter With {
		.CenterText = "Page {page} of {total-pages}",
		.DrawDividerLine = True
	}
End If
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
pdfDocument.RenderingOptions = renderOptions
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf")
$vbLabelText   $csharpLabel

在這個範例中,PdfGenerationSettings 類利用 C# Primary Constructor 來初始化與 PDF 產生設定相關的屬性,之後可以利用這些屬性來找出要新增哪些呈現選項以及跳過哪些選項。輸出包含一個標頭文字和標題,因為它是使用主構造器參數設定的。

C# Primary Constructor (How It Works For Developer):圖 3 - 上述程式碼範例的輸出 PDF

結論

總而言之,C# 中的主要構建器提出了一種精煉且具表達力的類別初始化方法。 它們的宣告式語法可增強程式碼的可讀性、促進不變性,並簡化以預設值建立物件的過程。 無論您是定義屬性、執行不變性或接受預設值,Primary Constructors 都能讓開發人員在 C# 程式設計的動態世界中掌握類別初始化的藝術。

雖然 C# Primary Constructors 與 IronPDF 的直接整合可能不是主要重點,但這兩個元素可以和諧合作。 C# Primary Constructors 增強了類別初始化的清晰度和簡易性,使其在定義與 IronPDF 工作流程相關的結構或配置時非常有價值。

利用 IronPDF 的強大功能來產生穩健的 PDF,並採用 C# Primary Constructors,其中類別初始化的優雅性是最重要的。 在 C# 程式設計這個充滿活力的世界裡,這對充滿活力的雙人組能讓您以創意和效率來駕馭複雜的文件產生。

IronPDF 提供免費試用,其精簡版授權起價為 $999。

常見問題解答

主要構造函數如何使 C# 代碼更簡潔?

主要構造函數允許您直接在類聲明中聲明和初始化屬性,從而減少樣板代碼並提高可讀性。

C# 12 引入了哪些新功能?

C# 12 引入了主要構造函數、攔截器和集合表達式,這些功能共同為開發人員提供了更簡潔和強大的語法選項。

主要構造函數可以與不可變資料結構一起使用嗎?

是的,主要構造函數非常適合不可變資料結構,因為它們允許直接在構造函數中初始化只讀屬性。

如何使用 C# 將 HTML 內容轉換為 PDF?

您可以使用 IronPDF 的 ChromePdfRenderer 類將 HTML 內容轉換為 PDF,確保輸出文檔中的格式和樣式得以保留。

使用 IronPDF 進行 PDF 生成有什麼優勢?

IronPDF 提供了一個強大的平台來在 C# 中創建和操作 PDF 文件,支援 HTML 到 PDF 的轉換、PDF 合併和詳細的樣式保留等功能。

主要構造函數如何增強依賴注入?

主要構造函數通過在構造函數參數中明確指出類的依賴性來增強依賴注入,從而簡化依賴關係圖的設置和維護。

主要構造函數如何與 PDF 文檔生成進行整合?

使用像 IronPDF 這樣的庫時,主要構造函數可以用於初始化與 PDF 設置相關的配置類或結構,從而簡化設置過程。

主要構造函數的一些實際應用例子有哪些?

實際應用例子包括幾何形狀層次結構的初始化,以及需要清晰和簡潔的依賴注入場景。

開發人員如何開始在他們的項目中使用 IronPDF?

開發人員可以通過程序包管理控制台或 NuGet 包管理器安裝 IronPDF NuGet 包,並參考詳細的文檔以獲取實施細節。

IronPDF 在文檔生成工作流中扮演什麼角色?

IronPDF 通過允許開發人員輕鬆創建、轉換和操作 C# 中的 PDF,來增強文檔生成工作流,並支持與其他 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 小時在線上。
聊天
電子郵件
打電話給我