C#:const 和readonly的區別

來源:互聯網
上載者:User
  1. const欄位只能在該欄位的聲明中初始化;readonly欄位可以在聲明或者建構函式中初始化。因此,根據所使用的建構函式,readonly欄位可能具有不同的值
  2. const欄位為編譯時間常數;readonly欄位可用於運行時常數
  3. 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。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.