C# 中的 Const、Static 和 Readonly

csharpprogrammingserver side programming更新于 2024/10/7 9:56:00

Const

常量字段是无法修改的字段。在声明时,您需要为其分配一个值。

const int a = 5;

Static

如果将 static 修饰符应用于类,则您无法使用 new 关键字实例化该类。您可以在方法、属性、类、构造函数等上使用 static 关键字。

static int a = 10;

Readonly

Readonly 字段在声明时初始化,也可以在构造函数中设置它。

让我们看一个在构造函数内初始化 readonly 字段的示例。

示例

class Demo {
   readonly int a;
   public Demo( ) {
      a = 5;
   }
}

相关文章