您的位置:首页 > 其它

readonly和const的区别

2016-08-24 12:08 239 查看
readonly为运行时常量,const为编译时常量

编译时常量被运行时常量快,性能好,但缺乏灵活性(编译时常量需要重新编译应用程序); 
编译时常量(const)仅限于数值和字符串(基元类型),C#不允许使用new来初始化一个编译时常量; 
const修饰的常量默认是静态的(类型); 
readonly修饰的字段可以在构造函数中被修改; 
使用const较之使用readonly的好处就是性能方面更好

举例说明

private static readonly int B = 10;
private static readonly int A = B * 10;
void Start()
{
Debug.Log (A); //A=100
Debug.Log (B); //B=10
}

private static readonly int A = B * 10;
private static readonly int B = 10;
void Start()
{
Debug.Log (A); //A=0
Debug.Log (B); //B=10
}

private const int A = B * 10;
private const int B = 10;
void Start()
{
Debug.Log (A); //A=100
Debug.Log (B); //B=10
}


用readonly时定义A,B的顺序,决定了A的值,说明readonly是运行时常量,运行的时候才能确定值,在B没有被赋值为10的时候,默认为0,所以A=B*10 最后的结果是0,而const是编译时常量,编译的时候就已经确定值,所以运行的时候不管B是否在A的前面,它的值都已经确定了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: