"The result is not considered to be constant" 是什么意思

What is meant with "The result is not considered to be constant"

MSDN中,我找到了这句话:

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

这是什么意思?他们的意思是编译器优化器不知道这个值是常量吗?我看不出这可能是相关的另一种方式。

编辑: 为什么这不被认为是常量?有合理的理由吗?

编辑:这段代码给出了x的编译错误,y却没有,为什么?:可以得到一个常量值,而[=13] =] 不能?

const string NULL = null;
const string val = "value";
const string x = NULL ?? val;
const string y = NULL == null ? val : NULL;

这意味着您不能在常量中使用空合并运算符:

public const int MyInt = 42; // Fine
public const int MyOtherInt = new int?(42) ?? 8; // Compiler error

这主要与大多数其他运算符不同,在其他运算符中,常量的操作数产生的结果也是常量:

public const int SomeResult = 12 + 42; // Fine
public const int OtherResult = SomeResult * 2; // Fine

这实际上不是 "optimisation" 的问题 - 事实上,?? 运算符在大多数情况下都经过了大量优化:

var someValue = new int?(42) ?? 8; // Produces ldc.i4.8

如果您编写的代码可能会导致此错误消息,答案将显而易见。

public void Test()
{
    const int x = ((int?)null ?? 3);
}

这会产生以下错误:

Error 9 The expression being assigned to 'x' must be constant

所以编译器在编译时不会计算??的结果。

相比之下,许多其他运算符如 ? : 是在编译时计算的,因此以下不会产生错误:

const int x = (true ? 3 : 2);

让我们考虑一下 ?? 的用法常量表达式中的运算符。原则上可以吗?当然,因为我们在编译时就有了所有需要的信息。它是在 C# 中实现的吗?没有。为什么?因为 C# 编译器团队 选择 不实现此功能。以下是Eric Lippert says关于选择应该实现的功能的内容:

Features have to be so compelling that they are worth the enormous dollar costs of designing, implementing, testing, documenting and shipping the feature. They have to be worth the cost of complicating the language and making it more difficult to design other features in the future.

我们什么时候可以使用??常量表达式中的运算符?当 expr-first 是空文字时。常量类型是对象或字符串(请记住,C# 团队已经决定不为常量添加 Nullables 支持)。此功能将 添加到语言中是什么?

const string s = null ?? "foo";

这不会给语言增加任何便利。和

完全一样
const string s = "foo";

但更复杂。