跳過到頁腳內容
.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 提供 免費試用,其 Lite license 起價為 $799 。

常見問題解答

主要構成式如何讓 C# 程式碼更簡潔?

Primary Constructors 可讓您直接在類別宣告中宣告和初始化屬性,減少模板程式碼的數量並提昇可讀性。

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

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

Primary Constructors 可以用於不可變的資料結構嗎?

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

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

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

使用 IronPDF 生成 PDF 有哪些優勢?

IronPDF 提供了一個強大的平台,用於在 C# 中建立和處理 PDF 檔案,支援 HTML 到 PDF 的轉換、PDF 合併和詳細的樣式保留等功能。

Primary Constructors 如何增強依賴注入功能?

Primary Constructors 透過在構建器參數中明確地指出類的相依性來增強相依性注入,從而簡化相依性圖表的設定與維護。

Primary Constructors 如何與 PDF 文件生成整合?

在使用 IronPDF 之類的函式庫時,Primary Constructors 可用於初始化與 PDF 設定相關的組態類別或結構,以簡化設定流程。

有哪些實例說明 Primary Constructors 的作用?

實用範例包括幾何形狀層級的初始化和依賴注入情境,在這些情境中,清晰和簡潔是不可或缺的。

開發人員如何開始在其專案中使用 IronPdf?

開發人員可透過套件管理員控制台或 NuGet 套件管理員安裝 IronPdf NuGet 套件,並參考全面的說明文件以瞭解實施細節。

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

IronPDF 可讓開發人員在 C# 中輕鬆建立、轉換和處理 PDF,支援與其他 C# 功能的無縫整合,從而增強文件生成工作流程。

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

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。