本质的区别在于,const的值是在编译期间确定的,因此只能在声明时通过常量表达式指定其值。而static readonly是在运行时计算出其值的,所以还可以通过静态构造函数来赋值。
那我们看看下面的语句能否互换:
1.static readonly TestClass test1=new TestClass(); 2.static readonly TestClass test2=null; 3.static readonly a=20*b; static readonly b=2; 4.static readonly int[] array=new int[]{1,2,3,4,5}; 5.void Test() { const int c=1; ... }
1:不可以换成const ,new操作符是需要执行构造函数的,是在执行的时候确定。
2:可以换成const ,Reference类型的常量可以是Null。
3:可以换成const ,在编译期间a=40.
4:不可以换成const,和1是一样的。
5:不可以换成readonly ,readonly只能用来修饰类的field,不能修饰局部变量,也不能修饰property等其他成员。
因此,对于那些本质上应该是常量,但是却无法使用const来声明的地方,可以使用static readonly。
再看下面的例子:
class Program { public static readonly Test test = new Test(); static void Main(string[] args) { test.Name = "Program"; //ok test = new Test(); // Error: } } class Test { public string Name; }
static readonly需要注意的一个问题是,对于一个static readonly的Reference类型,只是被限定不能进行赋值(写)操作而已。而对其成员的读写仍然是不受限制的。