首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 建構函式、解構函式、base、this 完整指南

     編輯:關於C#

建構函式

基本語法

  • 名稱與類別相同,無回傳型別 (連 void 都不能寫)。
  • 可多載 (參數不同)。
  • 無參建構函式為預設 (若未自訂任何建構函式)。
  • private 建構函式可防止外部實例化 (單例、工廠模式)。

建構函式鏈結 : this()

class Point
{
    public int X, Y;
    public Point() : this(0, 0) { }           // 呼叫雙參數版
    public Point(int x) : this(x, 0) { }      // 呼叫雙參數版
    public Point(int x, int y) { X = x; Y = y; } // 真正初始化邏輯
}
  • this(...) 必須是建構函式第一條語句。
  • 避免重複初始化代碼,集中邏輯於最完整的多載。

靜態建構函式

class Config
{
    public static string ConnectionString;
    static Config() // 無修飾詞、無參數、自動在第一次存取靜態成員/建立實例前執行一次
    {
        ConnectionString = LoadFromConfigFile();
    }
}
  • 用於初始化靜態欄位、執行一次性設定。
  • 執行時機由 CLR 保證 (線程安全、僅執行一次)。
  • 不可直接呼叫。

解構函式 (Finalizer)

class ResourceHolder : IDisposable
{
    private IntPtr _handle;
    ~ResourceHolder() // 語法: ~ClassName(),編譯為 Finalize()
    {
        Dispose(false);
    }
    // ... IDisposable 實作
}
  • 不可有參數、修飾詞、回傳值。
  • 由 GC 執行緒在物件回收前非決定性呼叫。
  • 不建議直接使用,優先實作 IDisposable 模式。
  • C# 無確定性解構 (C++ delete/RAII 不同)。

繼承與建構函式

自動呼叫基類建構函式

class Base { public Base() => Console.WriteLine("Base()"); }
class Derived : Base { public Derived() => Console.WriteLine("Derived()"); }

// new Derived() 輸出:
// Base()
// Derived()
  • 衍生類建構函式隱含呼叫基類無參建構函式 (base())。
  • 基類無無參建構函式時,必須用 base(...) 顯式指定。

base(...) 顯式呼叫基類建構函式

class Base
{
    public Base() { }
    public Base(int x) { }
    public Base(string s1, string s2) { }
}

class D1 : Base { public D1() : base() { } }           // 明確呼叫無參
class D2 : Base { public D2() : base(123) { } }        // 呼叫 int 版
class D3 : Base { public D3() : base("a", "b") { } }   // 呼叫 string 版

this 關鍵字完整用法

情境範例說明
限定同名欄位/參數this.name = name;區分欄位 name 與參數 name
建構函式鏈結public C() : this(0) { }呼叫同類別其他建構函式
索引子宣告public int this[int i] { get; }定義索引子
傳遞當前實例Other.Method(this);作為引數傳遞
比較實例身分if (this == other) ...參考比較
擴充方法接收者public static void Ext(this MyClass c) { }定義擴充方法 (static 類別中)

完整範例:建構函式鏈結 + 繼承 + base + this

abstract class Shape
{
    protected int _id;
    protected Shape(int id) => _id = id; // 受保護建構函式
    public int Id => _id;
}

class Rectangle : Shape
{
    public int Width { get; }
    public int Height { get; }

    // 完整建構函式
    public Rectangle(int id, int w, int h) : base(id)
    {
        Width = w; Height = h;
    }

    // 便利建構函式鏈結
    public Rectangle(int w, int h) : this(0, w, h) { }
    public Rectangle() : this(10, 10) { } // 預設 10x10
}

常見錯誤與最佳實踐

  1. 建構函式中呼叫虛擬方法:危險!衍生類覆寫方法可能存取尚未初始化的欄位。避免或改用工廠方法/初始化模式。
  2. 過度建構函式多載:超過 3-4 個考慮使用建構者模式或選項物件模式 (new Widget(new Options { ... }))。
  3. 靜態建構函式拋出例外:導致型別不可用 (TypeInitializationException),極難除錯。靜態建構函式務必簡單、不拋例外。
  4. 結構體建構函式:struct 不能有無參建構函式 (CLR 預設零值初始化),自訂建構函式必須初始化所有欄位。

總結

建構函式是物件生命週期的起點。善用 this() 鏈結消除重複、base() 正確初始化基類、static 建構函式處理靜態狀態、IDisposable 取代解構函式管理資源,能寫出正確、清晰、可維護的初始化邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved