C# 2.0 允許 get/set 指定不同存取層級,常見模式:public get + protected set(或 private set),實現「對外唯讀、衍生類可寫」的封裝。
public class MyClass
{
public string this[int index]
{
get { return _names[index]; }
protected set { _names[index] = value; } // 索引子 set 為 protected
}
private string[] _names;
}
public 屬性可用 internal/protected/private;protected 屬性不可用 public)。get 或 set,不可同時標註雙方。static class僅包含靜態成員、無需實例化的工具類/工廠類,C# 1.x 需私有建構函數防實例化;C# 2.0 原生支援:
public static class MyClassFactory
{
public static T CreateObject() where T : new() { return new T(); }
}
new MyClassFactory() 編譯錯誤)。sealed)。abstract(不可建立實例)。static MyClassFactory() { ... })。static 修飾。