return 的空合并运算符 (??)

Null coalescing operator (??) with return

我想知道为什么可以在 C# 7.0 中执行此操作:

int? test = 0;
int test2 = test ?? throw new Exception("Error");

..但不是这个:

int? test = 0;
int test2 = test ?? return;

谁能解释一下?

throw 最近(在 C# 7.0 中)被转换为一个表达式来启用它。 return 没有 - 它始终是一个公正的声明。 ?? 运算符需要表达式,而不是语句。这是 C# 设计者的任意选择,特别是允许使用 throw??

See the documentation on the throw expression

嗯,因为还没有人这样实现过。或者,更准确地说,因为 return 不是表达式。

throw 仅在 C# 7.0 之前是一个语句,但后来(由于提议)被扩展为一个表达式(空合并运算符仅支持表达式)。

所以除非没有人建议使 return 成为一个表达式,否则它不会起作用。