C# const和readonly的区别


  • 初始化赋值不同
  • const修饰的常量必须在声明的同时赋值,例如:
        public class Class1
        {
            public const int MaxValue = 10;//正确声明
            public const int maxValue;  //错误,常量字段要求提供一个值
            public Class1()
            {
                maxValue=10;
            }
        }

  • readonly字段可以在初始化(声明或构造函数)的过程中赋值。在其他地方不能进行赋值操作。根据所使用的构造函数,readonly可以具有不同的值
        public class Class2
        {
            public readonly int MaxValue = 10;//正确声明
            public readonly int maxValue;  //正确
            public readonly int minValue;   //正确
            public Class2(int i)
            {
                maxValue=10;
                minValue=i;
            }
        }

  • const字段是编译时的常数,而readonly可用于运行时的常数。
  • const默认就是静态的,而readonly如果设置成静态就必须显示声明。
  • const修饰的值的类型有限制,他只能是下列类型之一(或能够转换为下列类型):sbyte,byte,short,ushort,int,uint,long,char,float,double,decimal,bool,string,enum类型或引用类型。值得注意的是能够声明const的引用类型只能为string或者值为null的其它引用类型(例如:const Person p1=null;)。readonly可以是任何类型。
    static readonly Class c1=new Class1();
    //正确

  • object,Array,struct不能被声明为const常量
  • const和static readonly是否可以互换
          static readonly Class1 c1=new Class1();    //不可以换成const
            static readonly Class1 c1=null; //可以换成const
            static readonly int A=B*20; //可以换成const
            static readonly int B=10;   
            static readonly int[] constInArray=new int[]{1,2,3};//不可以换成const
            void SomeFunction() //不可以换成readonly,readonly只能用来修饰类的field,不能修饰局部变量,也不能修饰property等其他类成员
            {
                const int a=10;
            }
  • readonly只能用来修饰类的field,不能修饰局部变量,也不能修饰property等其他类成员

转载于:https://www.cnblogs.com/fornet/archive/2013/03/20/2976155.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值