常量和只读字段在C#中的含义是什么?

25 浏览
0 Comments

常量和只读字段在C#中的含义是什么?

这个问题已经有答案了:

可能是重复的问题:

什么是 const 和 readonly 的区别?

我对C#中的常量和只读有疑惑,请用简单的问题或任何参考资料来解释它们的区别。

admin 更改状态以发布 2023年5月24日
0
0 Comments

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 List canStillAddStrings = new List();
  void AddString(string toAdd) {
    canStillAddStrings.Add(toAdd);
  }
}

但在这种情况下,我们将无法替换引用:

class Foo {
  readonly List canStillAddStrings = new List();
  void SetStrings(List newList) {
    canStillAddStrings = newList; // <--- does not compile, assignment to readonly field
  }
}

0
0 Comments

const 在编译时就被初始化,不能被改变。

readonly 在运行时被初始化,但只能在构造函数或内联声明中进行一次。

0