.NET 幫助

C# 主構造函數(對開發人員的運作方式)

發佈 2024年1月14日
分享:

在 C# 程式設計的物件導向領域中,引入了主構造函數,為語言帶來了一個全新的優雅與簡單層面。主構造函數與攔截器和集合表達式等功能一同在 C# 12 中出現,作為一個強大的功能,提供了一種更簡潔的語法來聲明帶參數的構造函數。您可以深入探索主構造函數在 Microsoft C# 導覽在本文中,我們將學習如何有效地使用 C# 12 主構造函數,也將探討其功能、使用案例,以及它們如何改變開發人員進行類別初始化的方法。

基本了解:C# 中的构造函数

構造函數在物件導向程式設計中扮演著關鍵角色,作為初始化對象的藍圖。傳統上,C# 開發人員使用預設構造函數或參數化構造函數來設置其類別的初始狀態。然而,第一次構造函數(Primary Constructors)的引入為這一重要方面的 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 Integer Age {get;} = age public override String ToString()
	If True Then
		Return $"Name: {Name}, Age: {Age}"
	End If
End Class
VB   C#

在上述代碼片段中,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
VB   C#

在這個例子中,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
VB   C#

下面,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
VB   C#

主要構造函數適用於依賴注入場景。在這個例子中,一個控制器類別表明它的依賴性,增強了可維護性並促進單元測試。

範例 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
VB   C#

在這個範例中,Shape 類別的主要建構子形成了幾何形狀層次結構的基礎。像 RectangleCircle 這樣的子類別利用主要建構子進行一致的初始化。Rectangle 類別本身宣告了主要建構子,並將捕獲的主要建構子參數傳遞給 Shape 類別的主要參數。Circle 類別展示了靈活性,通過在整個類別中定義其建構子,然後使用 base 關鍵字將其參數作為 Shape 建構子的預設值進行傳遞。

介紹 IronPDF

IronPDF 是一個多功能的C#庫,使開發者能夠輕鬆地創建、操作和轉換PDF文件。無論是生成發票、報告或任何其他文件,IronPDF都能夠讓您在C#應用程式中無縫地將HTML內容轉換成精美而專業的PDF。

C# 主構造函數(對開發者的工作原理):圖1 - IronPDF 網頁

安裝 IronPDF:快速入門

要將 IronPDF 整合到您的 C# 專案中,首先需要安裝 IronPDF NuGet 套件。在包管理控制台中執行以下命令:

Install-Package IronPdf

或者,在 NuGet 程式套件管理員中找到 "IronPDF" 並從那裡進行安裝。

C# 主建構函式(其對開發人員的運作方式):圖 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")
VB   C#

在此範例中,IronPDF 用於將 HTML 內容渲染為 PDF 文件,然後將其保存到指定位置。有關在 C# 中創建和操作 PDF 的更多詳細信息,請訪問此完整 教學連結 如需了解更多,請訪問此 文檔 頁面。

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();
// Apply settings from PdfGenerationSettings
renderOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderOptions.MarginTop = 20;
renderOptions.MarginBottom = 20;
renderOptions.MarginLeft = 10;
renderOptions.MarginRight = 10;
renderOptions.Title = pdfSettings.Title ?? string.Empty;
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();
// Apply settings from PdfGenerationSettings
renderOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderOptions.MarginTop = 20;
renderOptions.MarginBottom = 20;
renderOptions.MarginLeft = 10;
renderOptions.MarginRight = 10;
renderOptions.Title = pdfSettings.Title ?? string.Empty;
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()
' Apply settings from PdfGenerationSettings
renderOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderOptions.MarginTop = 20
renderOptions.MarginBottom = 20
renderOptions.MarginLeft = 10
renderOptions.MarginRight = 10
renderOptions.Title = If(pdfSettings.Title, String.Empty)
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")
VB   C#

在此範例中,PdfGenerationSettings 類別利用 C# 主要建構子來初始化與 PDF 生成設置相關的屬性。之後可以用來決定要加入哪些渲染選項以及跳過哪些選項。因為使用了主要建構子參數設置,輸出包含標題文字和標題。

C# 主建構函式(它對開發者的運作方式):圖 3 - 上述程式碼範例生成的 PDF

結論

總結來說,C# 中的主構造函式提供了一種精緻且富有表現力的類初始化方法。它們的聲明式語法增強了代碼的可讀性,促進了不變性,並簡化了創建具有默認值的對象的過程。無論是定義屬性、強制不變性還是擁抱默認值,主構造函式都讓開發人員在C#編程的動態世界中掌握類初始化的藝術。

雖然C#主構造函式與IronPDF的直接集成可能不是主要關注點,但這兩個元素可以和諧地一起工作。C# 主構造函式增強了類初始化的清晰度和簡易性,使它們在定義與IronPDF工作流程相關的結構或配置時非常有價值。

利用IronPDF的強大功能進行穩健的PDF生成,並在類初始化優雅性至關重要時使用C#主構造函式。這一動態雙人組使您能夠以創造性和高效率在充滿活力的C#編程世界中應對文檔生成的複雜性。

IronPDF 提供... 免費試用 及其 Lite 授權 從 $749 開始。

< 上一頁
Null 合併運算子 C#(開發人員如何使用)
下一個 >
C# 雙問號(它如何為開發人員工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >