C# 初始化關鍵字 (如何為開發人員運作)
C# 9.0 中的init關鍵字引入了一種新的定義類屬性的方法,用於創建不可變的物件。 在 C# 的早期版本中,properties 通常與 get 和 set 存取器一起使用,以從物件欄位讀取或寫入物件欄位。 但是,使用 init,您可以僅在物件初始化時使屬性可寫,之後使其成為唯讀。
本教學將以 IronPDF 函式庫的實用範例和情境,探索如何使用 C# init 關鍵字。 您也將學習到傳統的屬性設定器 (set) 與新的僅限於 init 的設定器之間的關鍵差異。
Init 關鍵字的基本範例
讓我們從一個基本的例子開始:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
var person = new Person
{
FirstName = "Iron",
LastName = "Dev"
};
// person.FirstName = "Jane"; // This will give a compile-time error.public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
var person = new Person
{
FirstName = "Iron",
LastName = "Dev"
};
// person.FirstName = "Jane"; // This will give a compile-time error.Public Class Person
Public Property FirstName() As String
Public Property LastName() As String
End Class
Private person = New Person With {
.FirstName = "Iron",
.LastName = "Dev"
}
' person.FirstName = "Jane"; // This will give a compile-time error.
。
在此示例中,FirstName 和 LastName 被標示為啟始專用屬性。 這表示它們只能在物件初始化時指定。 物件建立後,嘗試變更數值會導致編譯時錯誤。
為什麼要使用 Init 關鍵字?
使用 init 關鍵字的主要原因是要讓物件的屬性在初始化後不可變。 傳統上,您可以將屬性標示為唯讀,以達到不變的目的。 然而,您通常會需要一個能接受所有必要值的建構器來設定欄位,這可能會導致建構器產生模板程式碼。 使用 init,您可以使用物件初始化器達到相同的目標,而不需要撰寫冗長的建構器。
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
// Without using constructor boilerplate for property initialization
}
var person = new Person
{
FirstName = "John",
LastName = "Doe"
};public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
// Without using constructor boilerplate for property initialization
}
var person = new Person
{
FirstName = "John",
LastName = "Doe"
};Public Class Person
Public Property FirstName() As String
Public Property LastName() As String
' Without using constructor boilerplate for property initialization
End Class
Private person = New Person With {
.FirstName = "John",
.LastName = "Doe"
}Object Initialization with Init-Only Properties
使用僅初始化屬性進行物件初始化。使用 init 可與物件初始化器無縫配合。 您可以在建立物件時直接定義所需的屬性,而不必仰賴建構器來設定值。
public class Point
{
public int X { get; init; }
public int Y { get; init; }
}
var point = new Point { X = 10, Y = 20 };
// point.X = 30; // This will throw a compile-time errorpublic class Point
{
public int X { get; init; }
public int Y { get; init; }
}
var point = new Point { X = 10, Y = 20 };
// point.X = 30; // This will throw a compile-time errorPublic Class Point
Public Property X() As Integer
Public Property Y() As Integer
End Class
Private point = New Point With {
.X = 10,
.Y = 20
}
' point.X = 30; // This will throw a compile-time error這會建立一個類型為 Point 的簡單、不可變的物件。 請注意,X 和 Y 的值是在初始化時設定的,之後不能修改。
將 init 與 Constructors 混合。
雖然 init 的主要用例是透過物件初始化器來初始化物件,但若有需要,您仍可使用構建器。 在物件建立過程中強制執行特定的屬性值時,這一點尤其有用。
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}Public Class Person
Public Property FirstName() As String
Public Property LastName() As String
Public Sub New(ByVal firstName As String, ByVal lastName As String)
Me.FirstName = firstName
Me.LastName = lastName
End Sub
End Class您可以同時使用構建器和 init 屬性。 此方法提供更多的彈性,同時在物件建構後仍能強制執行不可變性。
Init Over Private Set 的優點
以前,開發人員使用私有的 set accessor 來限制在類別之外的屬性修改。
public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}public class Person
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}Public Class Person
Private privateFirstName As String
Public Property FirstName() As String
Get
Return privateFirstName
End Get
Private Set(ByVal value As String)
privateFirstName = value
End Set
End Property
Private privateLastName As String
Public Property LastName() As String
Get
Return privateLastName
End Get
Private Set(ByVal value As String)
privateLastName = value
End Set
End Property
Public Sub New(ByVal firstName As String, ByVal lastName As String)
Me.FirstName = firstName
Me.LastName = lastName
End Sub
End Class儘管這種方法可行,但需要使用構建器的模板程式碼來初始化屬性。 此外,它允許類本身稍後修改屬性,這對不可變的物件來說並不總是理想的做法。 init 關鍵字消除了這個問題,因為它只允許在物件建立時進行初始化,之後的任何修改都會被阻擋。
使用唯讀欄位和初始存取器處理初始化。
init 關鍵字可以在建立物件時初始化欄位或屬性,而之後這些欄位或屬性仍保持不變。 唯讀欄位提供不變性,而 init 存取器則為屬性提供類似的功能。 這裡有兩種處理不可變性的方法:使用唯讀欄位和 init 屬性。
使用構成器的唯讀欄位
在這個範例中,我們使用 firstName 和 lastName 的唯讀欄位,這些欄位會在物件建構時設定。 這些欄位只能在構建器中指定一次,之後不能修改:
public class Person
{
private readonly string firstName;
private readonly string lastName;
public string FirstName => firstName;
public string LastName => lastName;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}public class Person
{
private readonly string firstName;
private readonly string lastName;
public string FirstName => firstName;
public string LastName => lastName;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}Public Class Person
'INSTANT VB NOTE: The field firstName was renamed since Visual Basic does not allow fields to have the same name as other class members:
Private ReadOnly firstName_Conflict As String
'INSTANT VB NOTE: The field lastName was renamed since Visual Basic does not allow fields to have the same name as other class members:
Private ReadOnly lastName_Conflict As String
Public ReadOnly Property FirstName() As String
Get
Return firstName_Conflict
End Get
End Property
Public ReadOnly Property LastName() As String
Get
Return lastName_Conflict
End Get
End Property
Public Sub New(ByVal firstName As String, ByVal lastName As String)
Me.firstName_Conflict = firstName
Me.lastName_Conflict = lastName
End Sub
End Class使用 Init Accessor 進行初始化
另外,我們也可以使用 init 存取器來建立唯讀的屬性,這些屬性可以在物件建立時初始化,但之後就無法變更。 這樣就不需要只讀欄位,並提供更現代化的語法:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}Public Class Person
Public Property FirstName() As String
Public Property LastName() As String
End ClassIronPDF 簡介

IronPDF是專為 C# 開發人員設計的功能強大的 PDF 產生和處理函式庫。 它簡化了使用 PDF的工作,將 HTML、CSS、圖片和其他內容轉換成 PDF 文件。 IronPDF 具備像素完美渲染、跨平台支援以及輕鬆整合至 .NET 專案等功能,是需要快速建立高品質 PDF 的開發人員的理想選擇。 您可以在 .NET Core、Framework 和 Standard 上使用它,而且它支援多種平台,包括 Windows、Linux 和 macOS。
案例:使用 IronPDF 與 C# Init 關鍵字。
若要在 C# 專案中建立不可變的物件,同時產生 PDF,您可以結合 init 關鍵字與 IronPDF。 init 關鍵字可確保物件初始化後的完整性,而 IronPDF 則會根據該不可變模型處理資料並產生 PDF。
確保 IronPDF 在您的專案中被正確引用。 您可以透過 NuGet 安裝:
Install-Package IronPdf
以下是程式碼範例:
using IronPdf;
public class Person
{
public int Id { get; init; }
public string FirstName { get; init; }
public string LastName { get; init; }
}
public class PDFGenerator
{
public static void CreatePersonPDF(Person person)
{
var htmlContent = $@"
<html>
<body>
<h1>Person Information</h1>
<p>ID: {person.Id}</p>
<p>First Name: {person.FirstName}</p>
<p>Last Name: {person.LastName}</p>
</body>
</html>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs($"Person_{person.Id}.pdf");
}
}
class Program
{
static void Main(string[] args)
{
var person = new Person
{
Id = 1,
FirstName = "Iron",
LastName = "Dev"
};
PDFGenerator.CreatePersonPDF(person);
}
}using IronPdf;
public class Person
{
public int Id { get; init; }
public string FirstName { get; init; }
public string LastName { get; init; }
}
public class PDFGenerator
{
public static void CreatePersonPDF(Person person)
{
var htmlContent = $@"
<html>
<body>
<h1>Person Information</h1>
<p>ID: {person.Id}</p>
<p>First Name: {person.FirstName}</p>
<p>Last Name: {person.LastName}</p>
</body>
</html>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs($"Person_{person.Id}.pdf");
}
}
class Program
{
static void Main(string[] args)
{
var person = new Person
{
Id = 1,
FirstName = "Iron",
LastName = "Dev"
};
PDFGenerator.CreatePersonPDF(person);
}
}Imports IronPdf
Public Class Person
Public Property Id() As Integer
Public Property FirstName() As String
Public Property LastName() As String
End Class
Public Class PDFGenerator
Public Shared Sub CreatePersonPDF(ByVal person As Person)
Dim htmlContent = $"
<html>
<body>
<h1>Person Information</h1>
<p>ID: {person.Id}</p>
<p>First Name: {person.FirstName}</p>
<p>Last Name: {person.LastName}</p>
</body>
</html>"
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs($"Person_{person.Id}.pdf")
End Sub
End Class
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim person As New Person With {
.Id = 1,
.FirstName = "Iron",
.LastName = "Dev"
}
PDFGenerator.CreatePersonPDF(person)
End Sub
End Class結論
。
總而言之,C# init 關鍵字允許您建立不可變的物件,同時在物件初始化時提供彈性。 它是私有集存取器的一個更乾淨、更安全的替代方案,減少了對構建器模板程式碼的需求。 將 init 關鍵字與唯讀欄位、結構及驗證邏輯相結合,可協助您建立強大且安全的資料結構,在不犧牲可讀性或彈性的情況下,保留不變性。 IronPdf 提供 免費試用,而授權費則從 $799 起。 這可讓您使用其完整功能,包括編輯、壓縮和保護 PDF。
常見問題解答
如何在 C# 中將 HTML 轉換為 PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換成 PDF。您也可以使用 RenderHtmlFileAsPdf 將 HTML 檔案轉換成 PDF。
C# 中的 init 關鍵字有何作用?
init 關鍵字允許您定義只能在物件初始化時設定的屬性,以確保初始化後的不變性。此功能對於建立一旦建立就不應改變的物件特別有用。
init 關鍵字如何增強 C# 中物件的不變性?
init 關鍵字使屬性只能在物件的初始化階段設定,以防止之後的任何變更。這可確保物件在建立後保持不變。
init 屬性是否可與函式庫一起使用以產生 PDF?
是的,init 屬性可與 IronPDF 等函式庫搭配使用,從不可變的物件產生 PDF,確保 PDF 所使用的資料在整個過程中保持一致。
使用 init 關鍵字比起傳統的 setters 有什麼優勢?
使用 init 關鍵字而非傳統的 setters 可促進不變性,減少對冗長的構建程式碼的需求,並確保物件的屬性在初始化後無法修改。
如何在 C# 中整合 PDF 生成與不可變屬性?
您可以使用 init 屬性建立不可變的物件,並將這些物件傳給 IronPDF,IronPDF 可以利用這些資料產生一致且可靠的 PDF 文件。
init 關鍵字在建立現代 C# 應用程式中扮演什麼角色?
init 關鍵字在建立現代 C# 應用程式的過程中扮演著重要的角色,它能讓開發人員使用簡潔的語法定義不可變的物件、增強程式碼的安全性,並減少 bug。
如何在 C# 專案中安裝 PDF 生成函式庫?
您可以使用 NuGet Package Manager 指令在 C# 專案中安裝 IronPDF 之類的函式庫:Install-Package IronPdf。
為什麼應用程式開發中的不變性很重要?
不可重复性非常重要,因为它可以确保整个应用程序的数据完整性和一致性,使其更易于维护并降低出现错误的可能性。
有哪些實例可以說明 init 關鍵字的用法?
一個實用的範例是使用 init 關鍵字來定義一個具有只能在初始化時設定的屬性的類別,以確保所建立的物件保持不變。這在資料一致性非常重要的情況下特別有用。







