- const欄位只能在該欄位的聲明中初始化;readonly欄位可以在聲明或者建構函式中初始化。因此,根據所使用的建構函式,readonly欄位可能具有不同的值
- const欄位為編譯時間常數;readonly欄位可用於運行時常數
- const預設就是靜態,而readonly如果設定成靜態就必須顯示聲明
看看下面的語句中static readonly和const能否互換:
1. static readonly MyClass myins = new MyClass();不可以換成const。 new是需要執行建構函式的,所以無法在編譯期間確定2. static readonly MyClass myins = null;可以換成const。參考型別的常量(除了String)只能是Null3. static readonly A = B * 20; static readonly B = 10;可以換成const。我們可以在編譯期間很明確的說,A等於2004. static readonly int [] constIntArray = new int[] {1, 2, 3};不可以換成const。5. void SomeFunction() { const int a = 10; ... }
不可以換成const。readonly只能用來修飾類中的成員,const可以用來修飾類中的成員,也可以用來修飾函數中的局部變數
static readonly需要注意的一個問題是,對於一個static readonly的Reference類型,只是被限定不能進行賦值(寫)操作而已。而對其成員的讀寫仍然是不受限制的。 public static readonly MyClass myins = new MyClass();…myins.SomeProperty = 10; //正常myins = new MyClass(); //出錯,該對象是唯讀
例子:
1 using System; 2 class P 3 { 4 static readonly int A=B*10; 5 static readonly int B=10; 6 public static void Main(string[] args) 7 { 8 Console.WriteLine("A is {0},B is {1} ",A,B); 9 }10 }
正確的輸出結果是A is 0,B is 10
1 class P 2 { 3 const int A=B*10; 4 const int B=10; 5 public static void Main(string[] args) 6 { 7 Console.WriteLine("A is {0},B is {1} ",A,B); 8 } 9 10 }
正確的輸出結果是A is 100,B is 10
const是靜態常量,所以在編譯的時候就將A與B的值確定下來了(即B變數時10,而A=B*10=10*10=100),那麼Main函數中的輸出當然是A is 100,B is 10啦。而static readonly則是動態常量,變數的值在編譯期間不予以解析,所以開始都是預設值,像A與B都是int類型,故都是0。而在程式執行到A=B*10;所以A=0*10=0,程式接著執行到B=10這句時候,才會真正的B的初值10賦給B。