在这个代码片段中:
class ClassWithConstants
{
private const string ConstantA = "Something";
private const string ConstantB = ConstantA + "Else";
...
}
赋值是线性的吗?是否存在 ConstantB == "Else"
的风险?
在这个代码片段中:
class ClassWithConstants
{
private const string ConstantA = "Something";
private const string ConstantB = ConstantA + "Else";
...
}
赋值是线性的吗?是否存在 ConstantB == "Else"
的风险?
你总会得到“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 节中明确提到: 常量允许依赖于同一程序中的其他常量,只要这些依赖关系不是循环的。编译器会自动安排以适当的顺序评估常量声明。
这种字符串拼接发生在编译时,因为只涉及到字符串字面量(在编译器构建文献中搜索常量折叠)。
不用担心。
它应该始终评估为 "SomethingElse"。