抛出表达式不适用于布尔表达式?
Throw Expressions not working for Boolean expressions?
抛出表达式在这种情况下有效:
string myStr;
public MyObj( string myStr ) =>
this.myStr = myStr ?? throw new ArgumentNullException( "myStr" );
但是为什么这也不能编译?
bool isRunning;
public void Run() =>
isRunning = !isRunning || throw new InvalidOperationException( "Already running" );
From the original proposal on github:
A throw expression is permitted in only the following syntactic contexts:
- As the second or third operand of a ternary conditional operator
?:
- As the second operand of a null coalescing operator
??
- As the body of an expression-bodied lambda or method.
只有这三种情况可以使用 throw 表达式。因此,您在布尔表达式中使用 throw 未被涵盖并且不是有效语法。
答案是 "because the spec says I can't"。但更有趣的问题是,规范为什么这么说?简而言之,我认为这是因为它会弄乱布尔逻辑。 throw 表达式没有布尔值。抛出表达式只是语法上的快捷方式。只有当 throw 表达式的 return 值或缺少值无关紧要时,我们才能摆脱它。另一方面,要使布尔逻辑起作用,return 值 确实 很重要。
抛出表达式在这种情况下有效:
string myStr;
public MyObj( string myStr ) =>
this.myStr = myStr ?? throw new ArgumentNullException( "myStr" );
但是为什么这也不能编译?
bool isRunning;
public void Run() =>
isRunning = !isRunning || throw new InvalidOperationException( "Already running" );
From the original proposal on github:
A throw expression is permitted in only the following syntactic contexts:
- As the second or third operand of a ternary conditional operator
?:
- As the second operand of a null coalescing operator
??
- As the body of an expression-bodied lambda or method.
只有这三种情况可以使用 throw 表达式。因此,您在布尔表达式中使用 throw 未被涵盖并且不是有效语法。
答案是 "because the spec says I can't"。但更有趣的问题是,规范为什么这么说?简而言之,我认为这是因为它会弄乱布尔逻辑。 throw 表达式没有布尔值。抛出表达式只是语法上的快捷方式。只有当 throw 表达式的 return 值或缺少值无关紧要时,我们才能摆脱它。另一方面,要使布尔逻辑起作用,return 值 确实 很重要。