T t = new T();
Console.WriteLine("b:" + t.b); // 編譯錯誤
t.b 是 字段訪問表達式,其值類型為 int。但 Console.WriteLine("b:" + t.b) 中 + 運算符要求兩邊均為字符串或可隱式轉換。若 b 是 int,"b:" + t.b 會嘗試字符串拼接,**這本身是合法的**。
真正報錯原因通常是:
b 未聲明為 public 或 internal(默認 private),主函數在類外無法訪問。class T {
public int b; // 添加 public
public void fc() { Console.WriteLine("b:" + b); }
}
static void Main() {
T t = new T();
t.fc(); // 正確
Console.WriteLine("b:" + t.b); // 現正確
}
若字段為 private,需提供公共屬性或方法訪問,符合封裝原則。