- 初始化賦值不同
- const修飾的常量必須在聲明的同時賦值,例如:
public class Class1 { public const int MaxValue = 10;//正確聲明 public const int maxValue; //錯誤,常量字段要求提供一個值 public Class1() { maxValue=10; } }
- readonly字段可以在初始化(聲明或構造函數)的過程中賦值。在其他地方不能進行賦值操作。根據所使用的構造函數,readonly可以具有不同的值
public class Class2 { public readonly int MaxValue = 10;//正確聲明 public readonly int maxValue; //正確 public readonly int minValue; //正確 public Class2(int i) { maxValue=10; minValue=i; } }
- const字段是編譯時的常數,而readonly可用於運行時的常數。
- const默認就是靜態的,而readonly如果設置成靜態就必須顯示聲明。
- const修飾的值的類型有限制,他只能是下列類型之一(或能夠轉換爲下列類型):sbyte,byte,short,ushort,int,uint,long,char,float,double,decimal,bool,string,enum類型或引用類型。值得注意的是能夠聲明const的引用類型只能爲string或者值爲null的其它引用類型(例如:const Person p1=null;)。readonly可以是任何類型。
static readonly Class c1=new Class1(); //正確
- object,Array,struct不能被聲明爲const常量
- const和static readonly是否可以互換
static readonly Class1 c1=new Class1(); //不可以換成const static readonly Class1 c1=null; //可以換成const static readonly int A=B*20; //可以換成const static readonly int B=10; static readonly int[] constInArray=new int[]{1,2,3};//不可以換成const void SomeFunction() //不可以換成readonly,readonly只能用來修飾類的field,不能修飾局部變量,也不能修飾property等其他類成員 { const int a=10; }
- readonly只能用來修飾類的field,不能修飾局部變量,也不能修飾property等其他類成員
C# const和readonly的區別
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.