11

在这个片段中:

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

    ...

}

有结束的风险ConstantB == "Else"吗?还是分配是线性发生的?

4

3 回答 3

37

你总是会得到“SomethingElse”。这是因为 ConstantB 依赖于 ConstantA。

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

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

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

private const string ConstantB = ConstantA + "Else";
private const string ConstantA = "Something" + ConstantB;

错误:“ConsoleApplication2.Program.ConstantB”的常量值的评估涉及循环定义这种证明编译器知道它的依赖关系。


补充: Jon Skeet指出的规范参考:

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


于 2009-08-17T13:20:58.163 回答
3

这种字符串连接发生在编译时,因为只有字符串文字(在编译器构造文献中搜索常量折叠)。

别担心。

于 2009-08-17T13:05:37.313 回答
2

它应该始终评估为“SomethingElse”

于 2009-08-17T13:06:09.933 回答