2009-08-17 45 views
11

在这个片断:C#:此字段分配是否安全?

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

    ... 

} 

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

+0

@Svish,请参阅有关他的回答 – 2009-08-21 16:24:13

+0

@Nathan乔恩斯基特的评论,谢谢,没有注意到这个:P – Svish 2009-08-21 20:21:54

回答

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

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.


+2

是啊,你'对了 - 呃! :)试图找到规范中保证这一点... – 2009-08-17 13:32:33

+0

现在找到它 - 第10.4节。 – 2009-08-17 13:36:37

+3

编辑我的答案,至少它不会误导人们,但如果/当我可以的时候会删除它。 – 2009-08-17 13:37:59

3

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

别担心。

2

应该始终评估为 “SomethingElse”