C# 中的最终变量

来源:这里教程网 时间:2026-02-21 16:25:00 作者:

c# 中的最终变量

Java有final关键字,但C#没有它的实现。在 C# 中使用 seal 或 readonly 关键字来实现相同的实现。

readonly 允许变量仅被赋值一次。标记为“只读”的字段只能在对象构造期间设置一次。它无法更改。

示例

class Employee {
   readonly int age;
   Employee(int age) {
      this.age = age;
   }
   void ChangeAge() {
         //age = 27; // Compile error
   }
}

上面,我们将年龄字段设置为只读,一旦分配就无法更改。

相关推荐