编译时常量 const VS 运行时常量 readonly

//编译时常量

public const int constValue=100;

//运行时常量

public static readonly int readonlyValue=200;

 

代码将被编译成MSIL(微软中间语言),在MSIL中,constValue直接被100所替换,且以后不会再更改;readonlyValue则只是变成对其变量的引用,其值在以后还可以改变。

所以一般选择readonly变量,这样比较灵活;但是诸如PI等于3.1415926这种一百年不变的变量,可以使用const。

 

——摘自《Effective C#》

posted @ 2010-01-21 20:05  robin.won  Views(193)  Comments(0)    收藏  举报