C#中的const与readonly用法

一、const与readonly用法与区别

1.  const修饰的局部变量或字段属于静态常量,静态常量是在程序编译时就确定其值;readonly通常用来修饰字段,属于动态常量,动态常量是在运行时确定其值的。

2.  由于const是编译时常量,所以声明时必须初始化,而且const修饰的局部变量或字段不能添加static修饰符;readonly是运行时常量,其修饰的字段可以在声明或构造函数中进行初始化,readonly修饰的字段可以添加static修饰符,在被赋值后,其值也是不可以修改的。

3.  const修饰的常量注重效率,没有内存消耗,可以修饰的类型包括基元类型、字符串类型、枚举类型;readonly修饰的常量注重灵活性,需要内存消耗,可以修饰任何类型。

二、代码实例

1. 代码运行结果:
class Program
    {
        static readonly int A = B * 10;
        static readonly int B = 10;
        public static void Main(string[] args)
        {
            Console.WriteLine("A is {0},B is {1} ", A, B);
            Console.ReadLine();
        }
    }//输出:A  is  0, B  is  10

2. 语法检查

A. private const int FIRST_NUM = 1;//正确
B. private static const int FIRST_NUM = 1;//错误,const就是静态常量,不需要static修饰符

C. int  t  = 1; private const int FIRST_NUM = t  + 1;//错误

D.private  static  readonly  int  FIRST_NUM = 1;//正确

猜你喜欢

转载自blog.csdn.net/szzhuyike/article/details/81735501