先上两个例子:
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  字段可以在声明或构造函数中初始化。
 
编译时常量的性能稍微好点,但是在(系统)维护上有着深远的潜在影响。

相关文章:

  • 2021-11-29
  • 2021-07-08
  • 2021-07-08
  • 2021-10-16
  • 2021-08-04
  • 2021-12-11
  • 2021-11-17
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2022-12-23
  • 2021-12-19
  • 2021-07-27
  • 2021-10-17
相关资源
相似解决方案