readonly 关键字是可以在字段上使用的修饰符。当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中。在此示例中,字段 year 的值无法在 ChangeYear 方法中更改,即使在类构造函数中给它赋了值。

 CopyCode image复制代码
class Age
{
    readonly int _year;
    Age(int year)
    {
        _year = year;
    }
    void ChangeYear()
    {
        _year = 1967; // Will not compile.
    }
}

Expand 图像备注

Expand 图像示例

Expand 图像输出

Expand 图像C# 语言规范

Expand image请参见