const和readonly区别.docxVIP

  • 0
  • 0
  • 约8.35千字
  • 约 9页
  • 2017-08-06 发布于河南
  • 举报
const和readonly区别

我们都知道,const和static readonly的确很像:通过类名而不是对象名进行访问,在程序中只读等等。在多数情况下可以混用。二者本质的区别在于,const的值是在编译期间确定的,因此只能在声明时通过常量表达式指定其值。而static readonly是在运行时计算出其值的,所以还可以通过静态构造函数来赋值。明白了这个本质区别,我们就不难看出下面的语句中static readonly和const能否互换了:1. staticreadonlyMyClassmyins = new MyClass();2. staticreadonlyMyClassmyins = null;3. staticreadonly B = 10; static readonly A = B * 20;4. staticreadonlyint [] constIntArray = new int[] {1, 2, 3};5. voidSomeFunction() {constint a = 10; ... }6.private static string astr=abcd;private const string str = astr+efg;1:不可以换成const。new操作符是需要执行构造函数的,所以无法在编译期间确定2:可以换成const。我们也看到,Reference类

文档评论(0)

1亿VIP精品文档

相关文档