成員常數 以 const 宣告,值在編譯期確定並內嵌至呼叫端 IL,屬於靜態成員(不可再加 static)。
class A {
public const double X = 1.0, Y = 2.0, Z = 3.0; // 多重宣告
}
new、public、protected、internal、privatestatic、readonly、volatile| const | static readonly | |
|---|---|---|
| 評估時機 | 編譯期 | 執行期(建構函式) |
| 版本控制 | 呼叫端需重編譯 | 執行期讀取,無需重編譯 |
| 型別限制 | 基本型別/string/enum/null | 任意型別 |
// 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(static readonly 執行期讀取)
// 若為 const → Program2 仍輸出 1(需重編譯)