readonly与const - zLulus/My_Note GitHub Wiki
const与readonly
const需要在编译时分配一个值,readonly在运行时分配一个值。
const:
const的值是在编译时本身分配的,一旦分配,就不能更改。 它们本质上是静态的,我们不能将static关键字与const一起使用
。
它们也称为编译时常量
,因为它们的值必须在编译时本身设置。
readonly:
只读字段的值可以在声明
时设置,也可以在类的构造函数
中分配。
它们也称为运行时常量
,因为它们的值可以在运行时更改,但要注意的是它们只能在类的构造函数中更改。
const 与 static
static 定义的是静态变量.可以在外部改变它的值。
const和static readonly
const和static readonly的确非常像:通过类名而不是对象名进行访问,在函数中只读等等。在多数情况下能混用。
二者本质的差别在于,const的值是在编译期间确定的,因此只能在声明时通过常量表达式指定其值。而static readonly是在运行时计算出其值的,所以还能通过静态构造函数
来赋值。
private const int constNumber1 = 100;
private readonly int readonlyNumber1 = 100;
private static readonly int readonlyNumber2 = 100;
static UseConstAndReadonlyDemo()
{
//constNumber1 = 200;//X
//static readonly 可以在静态构造函数中赋值
readonlyNumber2 = 200;
}
public UseConstAndReadonlyDemo()
{
//constNumber1 = 200;//X
//readonly可以在构造函数中赋值
readonlyNumber1 = 200;
//readonlyNumber2 = 200;//X
}