C#中static和const有什么区别

们都知道,const和static readonly的确很像:经过类名而不是对象名进行访问,在程序中只读等等。在多数状况下能够混用。html

两者本质的区别在于,const的值是在编译期间肯定的,所以只能在声明时经过常量表达式指定其值。而static readonly是在运行时计算出其值的,因此还能够经过静态构造函数来赋值。 明白了这个本质区别,咱们就不难看出下面的语句中static readonly和const可否互换了:数组

1. static readonly MyClass myins = new MyClass();函数

2. static readonly MyClass myins = null;htm

3. static readonly A = B * 20; static readonly B = 10;对象

4. static readonly int [] constIntArray = new int[] {1, 2, 3};io

5. void SomeFunction() { const int a = 10; ... }编译

 

1:不能够换成const。new操做符是须要执行构造函数的,因此没法在编译期间肯定变量

2:能够换成const。咱们也看到,Reference类型的常量(除了String)只能是Null。百度

3:能够换成const。咱们能够在编译期间很明确的说,A等于200。构造函数

4:不能够换成const。道理和1是同样的,虽然看起来1,2,3的数组的确就是一个常量。

5:不能够换成readonly,readonly只能用来修饰类的field,不能修饰局部变量,也不能修饰property等其余类成员。

 

转自百度知道:https://zhidao.baidu.com/question/1573797199680010420.html