常量和只读字段在C#中的含义是什么?
常量和只读字段在C#中的含义是什么?
这个问题已经有答案了:
可能是重复的问题:
什么是 const 和 readonly 的区别?
我对C#中的常量和只读有疑惑,请用简单的问题或任何参考资料来解释它们的区别。
admin 更改状态以发布 2023年5月24日
const
是一个编译时的常量:你给出的值会在代码编译时插入到代码中。这意味着你只能使用编译器能够理解的类型作为常量值,比如整数和字符串。和 readonly
不同,你不能将函数的结果赋值给一个常量字段,例如:
class Foo { int makeSix() { return 2 * 3; } const int const_six = makeSix(); // <--- does not compile: not initialised to a constant readonly int readonly_six = makeSix(); // compiles fine }
而 readonly
字段则在运行时被初始化,可以有任何类型和值。标记了 readonly
的字段意味着这个字段一旦被赋值就不能再次被赋值。
需要注意的是,一个 readonly
的集合或对象字段仍然可以改变它的内容,只是不能改变设置的集合的标识。以下代码是完全合法的:
class Foo { readonly ListcanStillAddStrings = new List (); void AddString(string toAdd) { canStillAddStrings.Add(toAdd); } }
但在这种情况下,我们将无法替换引用:
class Foo { readonly ListcanStillAddStrings = new List (); void SetStrings(List newList) { canStillAddStrings = newList; // <--- does not compile, assignment to readonly field } }