C#:这个字段分配安全吗?

Svi*_*ish 11 c# field constants variable-assignment

在这个片段中:

class ClassWithConstants
{
    private const string ConstantA = "Something";
    private const string ConstantB = ConstantA + "Else";

    ...

}
Run Code Online (Sandbox Code Playgroud)

是否有结束的风险ConstantB == "Else"?或者这些分配是否线性发生?

Lui*_*ipe 37

你将永远得到"SomethingElse".这是因为ConstantB依赖于ConstantA.

你甚至可以切换线条,你会得到相同的结果.编译器知道ConstantB依赖于ConstantA并相应地处理它,即使你在部分类中编写它也是如此.

要完全确定您可以运行VS命令提示符并调用ILDASM.在那里你可以看到实际的编译代码.

此外,如果您尝试执行以下操作,您将收到编译错误:

private const string ConstantB = ConstantA + "Else";
private const string ConstantA = "Something" + ConstantB;
Run Code Online (Sandbox Code Playgroud)

错误:对'ConsoleApplication2.Program.ConstantB'的常量值的评估涉及循环定义.这类证明编译器知道其依赖性.


补充:Jon Skeet指出的Spec参考:

这在C#3规范的10.4节中明确提到:只要依赖关系不是循环性的,允许常量依赖于同一程序中的其他常量.编译器会自动安排以适当的顺序评估常量声明.


  • 编辑我的答案,至少它不会误导人,但如果/我什么时候会删除它. (3认同)
  • 是的,你是对的 - doh!:)试图在规范中找到保证这一点的位... (2认同)