简体   繁体   English

空合并运算符和抛出

[英]The null-coalescing operator and throw

I've just noticed that when using throw with the null-coalescing operator, you cannot just use the keyword "throw" on its own, an exception must be included with it.我刚刚注意到,在将 throw 与 null-coalescing 运算符一起使用时,您不能只使用关键字“throw”,它必须包含异常。 The following code demonstrates what I mean:以下代码演示了我的意思:

try
{
   return GetName();
}
catch (NameNotFoundException ex)
{
    string name = GetOtherName();
    // this is legal
    return name ?? throw ex;
    // whereas this is not
    return name ?? throw;
}

Is there any reason for this?这有什么原因吗? Would it be because throw;会不会是因为throw; doesn't constitute an expression, or is there more to it?不构成表达式,还是还有更多?

According to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/throw-expression根据https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/throw-expression

a throw expression consists of the throw keyword followed by a null_coalescing_expression where the null_coalescing_expression throw 表达式由 throw 关键字后跟 null_coalescing_expression 组成,其中 null_coalescing_expression

must denote a value of the class type System.Exception, of a class type that derives from System.Exception or of a type parameter type that has System.Exception (or a subclass thereof) as its effective base class.必须表示 class 类型 System.Exception 的值、从 System.Exception 派生的 class 类型或具有 System.Exception(或其子类)作为其有效基 ZA2F2ED4F8EBC2CBB4C21A29DC40 的类型参数类型的值。 If evaluation of the expression produces null, a System.NullReferenceException is thrown instead如果表达式的评估产生 null,则会引发 System.NullReferenceException

return name?? throw; does not satisfy this condition as only the throw expression would be allowed here, not a throw statement.不满足此条件,因为此处仅允许 throw 表达式,而不是 throw 语句。

At least that's how I read this.至少我是这么读的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM