[英]The null-coalescing operator and throw
我刚刚注意到,在将 throw 与 null-coalescing 运算符一起使用时,您不能只使用关键字“throw”,它必须包含异常。 以下代码演示了我的意思:
try
{
return GetName();
}
catch (NameNotFoundException ex)
{
string name = GetOtherName();
// this is legal
return name ?? throw ex;
// whereas this is not
return name ?? throw;
}
这有什么原因吗? 会不会是因为throw;
不构成表达式,还是还有更多?
throw 表达式由 throw 关键字后跟 null_coalescing_expression 组成,其中 null_coalescing_expression
必须表示 class 类型 System.Exception 的值、从 System.Exception 派生的 class 类型或具有 System.Exception(或其子类)作为其有效基 ZA2F2ED4F8EBC2CBB4C21A29DC40 的类型参数类型的值。 如果表达式的评估产生 null,则会引发 System.NullReferenceException
return name?? throw;
不满足此条件,因为此处仅允许 throw 表达式,而不是 throw 语句。
至少我是这么读的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.