.NET 幫助

C# 結構與類別(開發人員的運作方式)

發佈 2024年3月6日
分享:

在C#中,結構體(struct)和類(class)都是組織和存儲數據的基本構建塊,但它們具有不同的特點,使其適用於不同的情景。理解它們之間的區別 C# 結構體和類別 在設計 C# 應用程式時,對結構和類別之間的區別有深入了解是非常關鍵的。

在本文中,我們將探索結構和類別之間的主要區別,討論它們的使用情境、記憶體管理以及效能影響。此外,我們還會討論如何使用結構和類別與 IronPDF 用於建立 PDF 檔案。

結構體和類別概述

1.1. 類別 (參考類型)

引用類型: C# 中的類別是位於堆內存的引用類型,這意味著當創建一個類別的實例時,對象的引用會存儲在內存中。

堆分配: 類別實例在堆內存分配中分配內存,提供了靈活的大小並允許對象在代碼的不同部分之間共享。

默認構造函數: 如果未明確定義,類別可以有一個默認構造函數,該構造函數會自動提供。

繼承: 類別支持繼承,允許創建具有共享特性的派生類別。

using System;
// Define a class
public class MyClass
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyClass(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyClass: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the class
        MyClass myClassInstance = new MyClass(10);
        // Access field and call method
        myClassInstance.Display();
        // Classes are reference types, so myClassInstance refers to the same object in memory
        MyClass anotherInstance = myClassInstance;
        anotherInstance.MyField = 20;
        // Both instances refer to the same object, so the change is reflected in both
        myClassInstance.Display();
        anotherInstance.Display();
    }
}
using System;
// Define a class
public class MyClass
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyClass(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyClass: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the class
        MyClass myClassInstance = new MyClass(10);
        // Access field and call method
        myClassInstance.Display();
        // Classes are reference types, so myClassInstance refers to the same object in memory
        MyClass anotherInstance = myClassInstance;
        anotherInstance.MyField = 20;
        // Both instances refer to the same object, so the change is reflected in both
        myClassInstance.Display();
        anotherInstance.Display();
    }
}
Imports System
' Define a class
Public Class [MyClass]
	' Fields (data members)
	Public MyField As Integer
	' Constructor
	Public Sub New(ByVal value As Integer)
		MyField = value
	End Sub
	' Method
	Public Sub Display()
		Console.WriteLine($"Value in MyClass: {MyField}")
	End Sub
End Class
Friend Class Program
	Shared Sub Main()
		' Create an instance of the class
		Dim myClassInstance As [MyClass] = New [MyClass](10)
		' Access field and call method
		myClassInstance.Display()
		' Classes are reference types, so myClassInstance refers to the same object in memory
		Dim anotherInstance As [MyClass] = myClassInstance
		anotherInstance.MyField = 20
		' Both instances refer to the same object, so the change is reflected in both
		myClassInstance.Display()
		anotherInstance.Display()
	End Sub
End Class
VB   C#

C# 結構 vs 類別(開發人員如何使用):圖 1 - 上一段代碼在控制台中的輸出

1.2. 結構體 (Structs) (值類型)

值類型: Struct 是值類型,這意味著實際數據存儲在變量聲明的地方,而不是像原始類型那樣存儲在記憶體的其他位置。這也意味著在不使用 Nullable<> 標籤將其設為可空類型的情況下,struct 不能被賦予 null 值。

堆疊分配: Struct 實例的記憶體在堆疊上分配,這導致更快的分配和釋放,但在大小和範圍上有限制。

無預設建構函數: Struct 沒有預設的建構函數,除非明確定義了一個。在實例化過程中,每個欄位都必須被初始化。

無繼承: Struct 不支持繼承。它們主要用於輕量級數據結構。

using System;
// Define a struct
public struct MyStruct
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyStruct(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyStruct: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the struct
        MyStruct myStructInstance = new MyStruct(10);
        // Access field and call method
        myStructInstance.Display();
        // Structs are value types, so myStructInstance is a copy
        MyStruct anotherInstance = myStructInstance;
        anotherInstance.MyField = 20;
        // Changes to anotherInstance do not affect myStructInstance
        myStructInstance.Display();
        anotherInstance.Display();
    }
}
using System;
// Define a struct
public struct MyStruct
{
    // Fields (data members)
    public int MyField;
    // Constructor
    public MyStruct(int value)
    {
        MyField = value;
    }
    // Method
    public void Display()
    {
        Console.WriteLine($"Value in MyStruct: {MyField}");
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the struct
        MyStruct myStructInstance = new MyStruct(10);
        // Access field and call method
        myStructInstance.Display();
        // Structs are value types, so myStructInstance is a copy
        MyStruct anotherInstance = myStructInstance;
        anotherInstance.MyField = 20;
        // Changes to anotherInstance do not affect myStructInstance
        myStructInstance.Display();
        anotherInstance.Display();
    }
}
Imports System
' Define a struct
Public Structure MyStruct
	' Fields (data members)
	Public MyField As Integer
	' Constructor
	Public Sub New(ByVal value As Integer)
		MyField = value
	End Sub
	' Method
	Public Sub Display()
		Console.WriteLine($"Value in MyStruct: {MyField}")
	End Sub
End Structure
Friend Class Program
	Shared Sub Main()
		' Create an instance of the struct
		Dim myStructInstance As New MyStruct(10)
		' Access field and call method
		myStructInstance.Display()
		' Structs are value types, so myStructInstance is a copy
		Dim anotherInstance As MyStruct = myStructInstance
		anotherInstance.MyField = 20
		' Changes to anotherInstance do not affect myStructInstance
		myStructInstance.Display()
		anotherInstance.Display()
	End Sub
End Class
VB   C#

C# 結構體與類別(開發者如何運作):圖2 - 前面代碼在控制台的輸出

使用案例和指南

2.1. 何時使用類別

複雜狀態和行為: 當您需要為具有狀態和行為的複雜數據結構建模時,請使用類別。類別適合表示具有多個屬性和方法的複雜對象。

引用語義: 如果您希望共享對象實例並在程式碼的不同部分反映更改,則類別是合適的選擇。

2.2. 什麼時候使用結構體

簡單的數據結構: 結構體非常適合用來表示輕量級的簡單數據結構,如點、矩形、鍵值對,或是那些從邏輯上可以表示為單一值的結構體,類似於原始類型。

值語義: 當你偏好使用值語義並希望避免堆分配的開銷時,結構體是一個不錯的選擇。

性能考量: 在需要考量性能的場景下,尤其是對於那些小型且頻繁使用的對象,結構體在堆棧分配上會更高效。

3. 記憶體分配差異

3.1. 類別

引用計數: 類別實例的內存由垃圾收集器通過引用計數來管理。當對象不再有任何引用時,它們就會符合垃圾收集條件。

內存洩漏的潛在風險: 如果對引用處理不當,當對象不再需要時未能正確釋放,可能會導致內存洩漏。

3.2. 結構體

不依賴垃圾回收機制: 結構體不依賴垃圾回收機制,因為它們是值類型且管理方式不同。當它們超出作用域時會自動釋放內存。

有限的記憶體開銷: 與類相比,結構體的記憶體開銷較低,使它們在記憶體使用受到限制的情況下更加高效。

4. 性能考量

類別

間接存取: 由於類別實例是通過引用存取的,這增加了一個額外的間接層次,可能會引入輕微的性能開銷。

堆分配: 在堆上動態分配記憶體可能會導致物件建立和銷毀時間較長。

結構體

直接訪問: 結構體是直接訪問的,無需額外的間接層級。這可以為小型、經常使用的物件帶來更好的效能。

堆疊分配: 記憶體的堆疊分配提供了更快的結構體實例創建和銷毀。

5. 介紹 IronPDF

IronPDF 是一個強大的C#函式庫,專為在.NET應用程式中無縫生成、操作和渲染PDF而設計。使用IronPDF,開發人員可以輕鬆創建、修改和與PDF文檔互動,使其成為從HTML內容動態生成PDF到從現有文檔中提取數據等任務的必備工具。這個多功能的函式庫簡化了PDF相關功能,為開發人員提供了一整套全面的功能,以便在開發Web應用程式、桌面軟體或任何需要高效PDF處理的.NET專案時使用。

5.1 安裝 IronPDF

在深入研究代碼範例之前,您需要安裝 IronPDF。您可以使用 NuGet 套件管理員控制台或在專案中添加對 IronPDF 庫的引用來完成這項工作。以下步驟概述了安裝過程:

  1. NuGet 套件管理員控制台:
    :ProductInstall
  1. 軟體包管理工具界面: 在 NuGet 軟體包管理工具介面中搜尋 "IronPDF" 並安裝最新版本。

一旦安裝了 IronPDF,你就可以在你的 C# 應用程式中使用它來處理 PDF 檔案了。

5.2. 使用結構體和類與IronPDF

using IronPdf;
using System;
// Sample class
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
// Sample struct
struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}
class Program
{
    static void Main()
    {
        // Sample instances of class and struct
        Person person = new Person { Name = "John Doe", Age = 30 };
        Point point = new Point { X = 10, Y = 20 };
        // Create a new PDF document
        var renderer = new ChromePdfRenderer();
        // Add content with information from class and struct
        string content = $@"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Information in IronPDF</h1>
                                <p>Name: {person.Name}</p>
                                <p>Age: {person.Age}</p>
                                <p>Point X: {point.X}</p>
                                <p>Point Y: {point.Y}</p>
                            </body>
                            </html>";
        // Render HTML content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        // Save the PDF to a file
        pdf.SaveAs("InformationDocument.pdf");
    }
}
using IronPdf;
using System;
// Sample class
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
// Sample struct
struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}
class Program
{
    static void Main()
    {
        // Sample instances of class and struct
        Person person = new Person { Name = "John Doe", Age = 30 };
        Point point = new Point { X = 10, Y = 20 };
        // Create a new PDF document
        var renderer = new ChromePdfRenderer();
        // Add content with information from class and struct
        string content = $@"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Information in IronPDF</h1>
                                <p>Name: {person.Name}</p>
                                <p>Age: {person.Age}</p>
                                <p>Point X: {point.X}</p>
                                <p>Point Y: {point.Y}</p>
                            </body>
                            </html>";
        // Render HTML content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        // Save the PDF to a file
        pdf.SaveAs("InformationDocument.pdf");
    }
}
Imports IronPdf
Imports System
' Sample class
Friend Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class
' Sample struct
Friend Structure Point
	Public Property X() As Integer
	Public Property Y() As Integer
End Structure
Friend Class Program
	Shared Sub Main()
		' Sample instances of class and struct
		Dim person As New Person With {
			.Name = "John Doe",
			.Age = 30
		}
		Dim point As New Point With {
			.X = 10,
			.Y = 20
		}
		' Create a new PDF document
		Dim renderer = New ChromePdfRenderer()
		' Add content with information from class and struct
		Dim content As String = $"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Information in IronPDF</h1>
                                <p>Name: {person.Name}</p>
                                <p>Age: {person.Age}</p>
                                <p>Point X: {point.X}</p>
                                <p>Point Y: {point.Y}</p>
                            </body>
                            </html>"
		' Render HTML content to PDF
		Dim pdf = renderer.RenderHtmlAsPdf(content)
		' Save the PDF to a file
		pdf.SaveAs("InformationDocument.pdf")
	End Sub
End Class
VB   C#
  • Person 是一個樣本類別,表示具有 NameAge 屬性的人。
  • Point 是一個樣本結構,表示具有 XY 屬性的2D座標系統中的一個點。
  • 創建 Person 類別和 Point 結構的實例。
  • 然後將HTML內容渲染成PDF文檔,並將其保存為 "InformationDocument.pdf"。

5.2.1. 輸出 PDF 檔案

C# 結構體與類別(開發人員如何使用):圖 3 - 從前面的代碼輸出PDF檔案

6. 結論

總結而言,在使用C#結構體和類別之間的選擇取決於您的應用程式的具體需求和特性。作為引用類型的類別適合用於建模具有狀態和行為的複雜實體,支援繼承並便於共享實例。另一方面,作為值類型的結構體非常適合具有值語義的輕量級資料結構,在堆疊分配和直接訪問方面提供了性能優勢。

IronPDF提供一個 免費試用許可證 為使用者提供了認識 IronPDF 功能和特性的良機。欲了解更多關於 IronPDF 的資訊,請造訪以下網址 連結 並有關於使用 IronPDF 創建 PDF 文件的詳細教程可在以下位置獲得 連結.

< 上一頁
C# 初始化陣列(開發人員如何操作)
下一個 >
NPlot C# (如何為開發者工作)

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

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