C#:这个字段赋值安全吗?

标签 c# constants field variable-assignment

在这段代码中:

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/

相关文章:

c# - 将对象添加到对象列表

c# - 使用google Drive SDK下载文件

c# - Xamarin Android - BroadcastReceiver 问题 - 无法实例化接收器

perl - 我可以在 glob 运算符中使用 Perl 常量吗?

javascript - 是否可以在javascript的函数中定义一个全局常量

c++ - 常量函数参数作为静态数组大小?

c# - 选择不返回结果

javascript - 使用 JavaScript 划分输入字段

css - Odoo 10 : How to increase the field width?

mysql - 创建与现有表具有相同字段的 mysql 表