建構函式是類別實例化時自動執行的特殊方法,負責初始化物件狀態(欄位賦值、資源配置、驗證不變條件)。語法特徵:名稱與類別相同、無回傳型別(甚至不寫 void)。
| 類型 | 語法 | 用途 | 備註 |
|---|---|---|---|
| 預設/無參數 | public ClassName() { } | 最簡單實例化 | 若類別無任何建構函式,編譯器自動產生 |
| 帶參數 | public ClassName(int id, string name) { } | 建立時注入必要資料 | 可多載,參數型別/數量不同即可 |
| 靜態建構函式 | static ClassName() { } | 初始化靜態欄位、執行一次性設定 | 無參數、無存取修飾詞、在第一次存取類別前自動執行、執行緒安全 |
| 私有建構函式 | private ClassName() { } | 單例模式、工廠模式、防止外部直接 new | 搭配公用靜態工廠方法使用 |
| 這個呼叫 | public ClassName() : this(0, "") { } | 避免重複初始化邏輯,集中到最完整參數版本 | 在建構函式內部呼叫另一個建構函式 |
| 基底呼叫 | public Derived(int x) : base(x) { } | 衍生類別初始化基底部分 | 若基底無無參數建構函式,衍生類別必須显式呼叫 base() |
public class ConnectionSettings
{
public string Host { get; }
public int Port { get; }
public int TimeoutMs { get; }
public bool UseSsl { get; }
// 最完整版本:實際初始化邏輯集中於此
public ConnectionSettings(string host, int port, int timeoutMs, bool useSsl)
{
if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("Host 不可為空");
if (port <= 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port));
if (timeoutMs <= 0) throw new ArgumentOutOfRangeException(nameof(timeoutMs));
Host = host;
Port = port;
TimeoutMs = timeoutMs;
UseSsl = useSsl;
}
// 簡化版:預設常用值
public ConnectionSettings(string host, int port)
: this(host, port, 5000, true) { }
// 僅主機:預設標準埠
public ConnectionSettings(string host)
: this(host, 443) { }
// 無參數:測試/反序列化用(需謹慎)
public ConnectionSettings()
: this("localhost", 443) { }
}
public class AppConfig
{
public static string ConnectionString { get; private set; }
public static ILogger Logger { get; private set; }
// 保證在第一次存取任何靜態成員前執行一次,執行緒安全
static AppConfig()
{
ConnectionString = LoadConnectionString();
Logger = CreateLogger();
}
private static string LoadConnectionString() => "Server=.;Database=App;Trusted_Connection=True;";
private static ILogger CreateLogger() => new ConsoleLogger();
}
public sealed class Singleton
{
private static readonly Lazy _instance =
new Lazy(() => new Singleton(), LazyThreadSafetyMode.ExecutionAndPublication);
public static Singleton Instance => _instance.Value;
private Singleton() { } // 防止外部 new
public void DoWork() => Console.WriteLine("Singleton working...");
}
public class Animal
{
public string Name { get; }
public Animal(string name) => Name = name ?? throw new ArgumentNullException(nameof(name));
}
public class Dog : Animal
{
public string Breed { get; }
// 必須显式呼叫 base(name),因為 Animal 沒有無參數建構函式
public Dog(string name, string breed) : base(name)
{
Breed = breed;
}
}
// 建構函式:強制必要參數、不可變物件
var settings = new ConnectionSettings("api.example.com", 8080, 3000, false);
// 物件初始化器:可選屬性、可變物件
var settings2 = new ConnectionSettings { Host = "api.example.com", Port = 8080 };
// ⚠️ 編譯器不強制必要屬性,易造成狀態不完整
: this(...) 鏈接,避免重複代碼。建構函式是類別正確性的第一道防線。掌握多載鏈接、靜態/私有建構函式、基底呼叫規則、與物件初始化器的取捨,能寫出更安全、可測試、符合單一職責原則的類別設計。