class CFoo
{
public const int c = 1;
public readonly int r = 2; //public readonly int r 也正确
public CFoo()
{
//c = 11; //错误
r = 22; //正确
}
public void ChngValue()
{
//c = 1111; //错误
//r = 2222; //错误
}
}
void Page_Load(object sender, EventArgs e)
{
CFoo foo = new CFoo();
//foo.c = 111; //错误
//foo.r = 222; //错误
foo.ChngValue();
}
可以看出
- const 必须在声明时赋值,即必须初始化;而 readonly 在声明时不赋值也不报错。
- const 一旦赋值在任何地方都不能再修改其值;而 readonly 可以在类构造函数中再次修改。
相关阅读: