public class MyClass
{
// 宣告同時初始化
private readonly List _items = new List();
private readonly Dictionary _map = new Dictionary();
private const int DefaultCapacity = 100;
}
// ❌ 多餘:CLR 已保證零初始化
private int _count = 0;
private string _name = null;
private MyStruct _val = new MyStruct(); // 結構更糟:產生 initobj + 裝箱/拆箱
// ✅ 正確:直接宣告
private int _count;
private string _name;
private MyStruct _val;
// ❌ 重複初始化:初始化器跑一次,建構函式又蓋一次
public class MyClass
{
private List _items = new List();
public MyClass() { }
public MyClass(int capacity) { _items = new List(capacity); }
}
// ✅ 正確:移除初始化器,建構函式統一處理
public class MyClass
{
private readonly List _items;
public MyClass() : this(0) { }
public MyClass(int capacity) => _items = new List(capacity);
}
public static readonly Regex EmailPattern = new Regex(@"^[\w.]+@[\w.]+\.\w+$");
public static readonly Dictionary Cache = new Dictionary();
預設使用欄位初始化器。例外:初始化為預設值(零初始化已足夠)、建構函式需不同參數初始化。靜態欄位同樣受益。