在这段代码中:
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 指出的规范引用:
This is explicitly mentioned in section 10.4 of the C# 3 spec: Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order.
关于C#:这个字段赋值安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1287842/