跳過到頁腳內容
.NET幫助

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

在 C# 程式設計的物件導向領域中,主要構造函數的引入為語言帶來了新層次的優雅和簡易性。 主要構造函數與攔截器和集合表達式等功能一起在 C# 12 中出現,作為一個強大的功能,提供了一種更加簡潔的語法來聲明帶參數的構造函數。 您可以在 Microsoft C# 指南中深入探索主要構造函數。

在本文中,我們將學習如何有效使用 C# 12 主要構造函數,還將探索其功能、使用情況以及它們如何改變開發人員處理類初始化的方式。

理解基礎:C# 中的構造函數

構造函數在物件導向程式設計中扮演著關鍵角色,作為初始化物件的藍圖。 傳統上,C# 開發人員使用默認構造函數或參數化構造函數來設置類的初始狀態。 然而,主要構造函數的引入為 C# 開發的這一基本方面提供了一種更加精簡的方法。

主要構造函數的本質

C# 中的主要構造函數是一種在類聲明中直接聲明和初始化屬性的簡潔方法。 它簡化了定義和分配屬性值的過程,提供了一種更加聲明式和可讀的語法。

主要構造函數的優點

  1. 簡潔性: 主要構造函數提供了簡潔的語法,減少了樣板代碼,增強了可讀性。
  2. 作用域: 與傳統構造函數不同,主要構造函數中的參數在整個類或結構中都在作用域內,提供了靈活的使用方式。
  3. 默認值: 默認參數值簡化了物件的創建,使開發人員使用更加方便。

聲明主要構造函數

主要構造函數的語法涉及在類標頭中直接聲明屬性。 讓我們考慮一個基本的 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 類具有一個主要構造函數來初始化實例成員 Name 和實例成員 Age 屬性。 構造函數參數是用類或結構名稱聲明的,並且在定義公共屬性時,將參數值分配給它們。

示例 1:二維空間中的不變點

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# 主要構造函數(對開發人員的影響):圖例 1 - IronPDF 網頁

安裝IronPDF:快速入門

在包管理器控制台中執行以下命令: 或者,在NuGet包管理器中找到"IronPDF",然後從那裡進行安裝。

Install-Package IronPdf

使用IronPDF創建PDF是一個簡單的過程。

C# 主要構造函數(對開發人員的影響):圖例 2 - 在 NuGet 套件管理器瀏覽器中搜尋 IronPDF 套件

使用IronPDF生成PDF

使用 IronPDF 創建 PDF 是一個簡化的過程。 在此示例中,IronPDF用於將HTML內容呈現為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代碼示例資源以獲取更多創建PDF文檔的方法。 For more details on creating and manipulating PDFs in C#, please visit this complete tutorial link, and to explore more please visit this documentation page.

C# 主要構造函數:類初始化的革命

C# 主要構造函數提供了一種在類聲明內直接初始化類屬性的聲明性和精簡的方法。 讓我們探索這個優雅的功能是否可以與 IronPDF 無縫整合。

C# 主要構造函數與 IronPDF 的整合

C# 主要構造函數主要是一個語言功能,專注於類的初始化,它們與 IronPDF 的直接整合可能不是常見的使用情況。 IronPDF 的核心功能在於生成和處理 PDF 文件,而類初始化的細節可能不會直接與此工作流程對齊。

然而,開發人員可以在定義與 IronPDF 配置或數據模型相關的自定義類或結構時利用 C# 主要構造函數。 例如,如果您的應用程序需要特定的類結構來管理與 PDF 相關的設定或配置,C# 主要構造函數可以是一個有價值的工具,用於簡潔地初始化這些類。

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# 主要構造函數來初始化與 PDF 生成設置相關的屬性,後來可以用來確定要添加哪些渲染選項以及要跳過哪些。輸出包含一個標題文本和標題,因為它是在主要構造函數參數中設置的。

C# 主要構造函數(對開發人員的影響):圖例 3 - 從上面的代碼示例輸出的 PDF

結論

總之,C# 中的主要構造函數提供了一種精緻且富有表達力的類初始化方法。 它們的宣告性語法增加了代碼的可讀性,促進了不變性,簡化了創建具有默認值的物件過程。 無論您是在定義屬性、強制實現不變性,還是採用默認值,主要構造函數都使開發人員能夠在 C# 程式設計的動態世界中掌握類初始化的藝術。

雖然 C# 主要構造函數與 IronPDF 的直接整合可能不是主要關注點,但這兩個元素可以協調工作。 C# 主要構造函數提高了類初始化的清晰性和簡單性,使它們成為定義與 IronPDF 工作流程相關結構或配置的寶貴資源。

利用 IronPDF 的強大功能進行穩健的 PDF 生成,並在類初始化優雅至關重要的地方使用 C# 主要構造函數。 這對動態組合使您能夠在 C# 程式設計的活力世界中創意高效地處理文件生成的複雜性。

IronPDF offers a free trial and its lite license starts from $799.

常見問題解答

主要構造函數如何使 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# 功能的無縫集成。

Curtis Chau
技術作家

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

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