C#:const 和readonly的区别

  1. const字段只能在该字段的声明中初始化;readonly字段可以在声明或者构造函数中初始化。因此,根据所使用的构造函数,readonly字段可能具有不同的值
  2. const字段为编译时常数;readonly字段可用于运行时常数
  3. const默认就是静态的,而readonly如果设置成静态的就必须显示声明

看看下面的语句中static readonly和const能否互换:

1. static readonly MyClass myins = new MyClass();
不可以换成constnew是需要执行构造函数的,所以无法在编译期间确定
2. static readonly MyClass myins = null;
可以换成const。引用类型的常量(除了String)只能是Null
3. static readonly A = B * 20;
   static readonly B = 10;
可以换成const。我们可以在编译期间很明确的说,A等于200
4. static readonly int [] constIntArray = new int[] {1, 2, 3};
不可以换成const。
5. void SomeFunction()
   {
      const int a = 10;
      ...
   }
不可以换成constreadonly只能用来修饰类中的成员,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。

 

 

posted on 2013-02-28 16:37  LilianChen  阅读(753)  评论(2编辑  收藏  举报

导航