因为 C# 中的 const 必须是 compile-time 常量。因此,唯一有效的const 选项(对于大多数引用类型)是null。
string 是一个例外,您可以将其分配给字符串文字。
// allowed because string literals are compile-time
private const string Message = "Hello World";
您可以有一个readonly 字段,这将允许该字段仅在初始化程序或构造函数中设置。本质上,这类似于const,只是它是在运行时确定的,可以是static 或实例(所有const 字段自动为static)。
但是,应该注意readonly 引用只是意味着引用是只读的,这并不意味着它引用的对象也被读取-only(当然,除非对象在设计上是不可变的,例如string)。
例如:
private readonly List<string> validStrings = new List<string> { "Apple", "Orange", "Pear" };
尽管上面的validStrings 是readonly,但这仅意味着您不能通过将validStrings 分配给新的引用来更改它。 但是如果对象是可变的,你可以修改它所指的内容:
// allowed, you can change what it refers to
validStrings.Clear();
// disallowed, cannot change what the reference refers to outside of constructor
validStrings = new List<string> { "Other", "Stuff" };
希望这会有所帮助...