C#:这是字段赋值安全吗?
-
18-09-2019 - |
题
在此片断:
class ClassWithConstants
{
private const string ConstantA = "Something";
private const string ConstantB = ConstantA + "Else";
...
}
是否有与ConstantB == "Else"
结束了的风险?还是做assigments线性发生的呢?
解决方案
您将获得 “SomethingElse”。这是因为ConstantB取决于康斯坦察。
您甚至可以切换行,你会得到同样的结果。编译器知道ConstantB取决于康斯坦察,并相应地处理它,即使你把它写在部分类。
要完全相信你可以运行VS命令提示符,然后调用ILDASM。在那里,你可以看到实际的编译代码。
此外,如果你尝试做以下,你会得到一个编译错误:
private const string ConstantB = ConstantA + "Else";
private const string ConstantA = "Something" + ConstantB;
错误强>:关于“ConsoleApplication2.Program.ConstantB”的恒定值的评价涉及循环定义 这种证明编译器知道它的依赖
添加了:规格参考所指出乔恩斯基特:
此被明确地在部分中的C#3规范的10.4提到: 常数被允许,只要该依赖关系是一个圆形的性质不相同的程序内,以依赖于其他常数。编译器自动排列以适当的顺序来评估恒定声明。
其他提示
此字符串连接发生在编译时,因为只有字符串(搜索的常量合并强>在编译器构造文献)。
不要担心。
应该始终评估为 “SomethingElse”
不隶属于 StackOverflow