在 C# 中将字段标记为只读有什么好处?

csharpserver side programmingprogramming更新于 2025/9/29 12:07:17

readonly 关键字用于将成员变量声明为常量,但允许在运行时计算其值。这与使用 const 修饰符声明的常量不同,后者必须在编译时设置其值。使用 readonly,您可以在声明中或字段所属对象的构造函数中设置字段的值。

"readonly"修饰符总共可以在四种上下文中使用:

  • 字段声明

  • 只读结构体声明

  • 只读成员定义

  • Ref 只读方法返回

当我们使用字段声明上下文时,我们需要知道赋值只能在声明时或调用同一类的构造函数时发生。

示例

class Program{
   readonly string Name;
   public Program(){
      Name = "Name";
   }
   static void Main(string[] args){
      Program a = new Program();
      System.Console.WriteLine(a.Name);
      Console.ReadLine();
   }
}

输出

Name

readOnly Struct

public readonly struct Server{
   public readonly string Name;
   public Server(string name){
      Name = name;
   }
}
class Program{
   static void Main(string[] args){
      Server a = new Server("Domain Controller");
      System.Console.WriteLine(a.Name);
      Console.ReadLine();
   }
}

输出

Domain Controller

相关文章