您的位置:首页 > 编程语言 > C#

C# const和readonly的区别

2013-03-20 22:59 459 查看
初始化赋值不同

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等其他类成员
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: