readonly 欄位:宣告時或建構函式中可指派,其他場合唯讀。常搭配 static 形成常數替代方案。
public class Constants {
public static readonly double PI = 3.14159;
public static readonly Color White = new Color(255,255,255);
public static readonly int KByte = 1024;
}
| const | static readonly | |
|---|---|---|
| 值形成 | 編譯期 | 執行期 |
| 跨組件升級 | 呼叫端需重編譯 | 無需重編譯,自動取新值 |
// Program1.dll
namespace Program1 { public class A { public static readonly int X = 1; } }
// Program2.exe 參考 Program1
Console.WriteLine(Program1.A.X); // 1
// 修改 Program1: X=2,重編譯 Program1,不重編 Program2
// 執行 Program2 → 輸出 2(執行期讀取)
// 若為 const → 輸出 1(編譯期內嵌)
此特性極利於組件版本演進與相容性維護。