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的前面,它的值都已经确定了。
编译时常量被运行时常量快,性能好,但缺乏灵活性(编译时常量需要重新编译应用程序);
编译时常量(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的前面,它的值都已经确定了。
相关文章推荐
- const和readonly的区别
- Const 与 readonly的区别
- C#中 const 和 readonly 的区别
- what's the differences between readonly & const in C# 在C#中readonly和const的区别
- [C#]const 和 readonly 的区别
- C#中const与readonly字段的区别
- C#中 const 和 readonly 的区别
- C#中 const 和 readonly 的区别
- readonly const 区别
- const 和 readonly 的区别
- const 和 readonly 的区别
- const和readonly的联系和区别
- C#中 const 和 readonly 的区别
- C#中 const 和 readonly 的区别
- const 和 readonly 的区别 (引用别人的文章)
- readonly 和const的区别
- C#中 const 和 readonly 的区别
- 【心得】在C#中使用静态变量const和动态变量readonly的区别
- C#中 const 和 readonly 的区别
- C# const和readonly的区别(收藏于网络)