前言:
Const与readonly我们应该都用过,我们只知道这个关键字很像,都是通过类型访问,并且在程序中都是只读,但是很少有人能分清楚两个的差别,今天我们来细谈Const与readonly。
Const:
编译器通过const修饰符,用其值取代了使用它的变量,编译器知道常量的值。const修饰变量时,必须得赋值,必定在编译时就已明确并且恒定的
readonly
只读字段在运行期间可以通过构造函数指定,初始化时可以不赋值。
static void Main(string[] args) { Test test = new Test(); //构造方法只运行一次(因为是静态构造函数) Test test2 = new Test(); Console.WriteLine("结束-----"); } public class Test { static readonly int A=B*10 ; static readonly int B = 10; static readonly int A1 = 10; static readonly int B1 = A1 * 10; const int C = D * 10; const int D =10; const int C1 = 10; const int D1 = 10 * C1; static Test() { A = 4; Console.WriteLine("A is {0},B is {1} ", A, B); //A is 0,B is 10 Console.WriteLine("A1 is {0},B1 is {1} ", A1, B1); //A1 is 10,B1 is 100 Console.WriteLine("C is {0},D is {1} ", C, D); //C is 100,D is 10 Console.WriteLine("C1 is {0},D1 is {1} ", C1, D1); //C is 10,D is 100 } }
静态常量