const V.S readonly

先上两个例子:
1  
2         static readonly int A = B * 10;
3         static readonly int B = 10;
4         static void Main(string[] args)
5         {
6             Console.WriteLine("A is {0},B is {1}", A, B);
7         }

输出结果为"A is 0,B is 10"   (若第一二行换一下顺序,则输出同下) 

        const int A = B * 10;
        const int B = 10;
        static void Main(string[] args)
        {
            Console.WriteLine("A is {0},B is {1}", A, B);
        }

输出结果为"A is 100,B is 10"

 
其根本原因在于const是编译时常量,值在编译时就已确定,而readonly是运行时常量,在运行时确定其值。
 
另外,const  字段只能在该字段的声明中初始化。 readonly  字段可以在声明或构造函数中初始化。
 
编译时常量的性能稍微好点,但是在(系统)维护上有着深远的潜在影响。
原文地址:https://www.cnblogs.com/ldm1989/p/3680531.html