我怎样才能强制将throw用作语句而不是表达式(在lambda表达式中)? [英] How can I force a throw to be a statement and not an expression (in a lambda expression)?
问题描述
从C#7.0开始,throw
关键字既可以用作表达式也可以用作语句,这很好.
不过,请考虑这些重载
Starting from C# 7.0 the throw
keyword can be used both as an expression and as a statement, which is nice.
Though, consider these overloads
public static void M(Action doIt) { /*use doIt*/ }
public static void M(Func<int> doIt) { /*use doIt*/ }
当这样调用时
M(() => throw new Exception());
甚至是这样(带有lambda语句)
or even like this (with a statement lambda)
M(() => { throw new Exception(); });
由编译器选择M(Func<>)重载,指示在这里将throw视为表达式. 我怎样才能优雅而明确地迫使编译器选择M(Action)重载?
the M(Func<>) overload is selected by the compiler indicating that the throw is here considered as an expression. How can I elegantly and intent-clear force the compiler to select the M(Action) overload?
做到这一点的一种方法是
One way to do it is this
M(() => { throw new Exception(); return; });
但是return语句的原因似乎并不明显,并且存在被下一个开发人员更改的风险,尤其是因为Resharper警告无法访问的代码.
but the reason for the return statement seems non-obvious, and runs the risk of being changed by the next developer especially since Resharper warns about the unreachable code.
(当然,我可以更改方法命名以避免重载,但这不是问题.:-)
(Of course I can change the method naming to avoid overloading, but that is not the question. :-)
推荐答案
您可以为Action
添加类型转换,尽管它确实带有所有括号,但 LISP'y 有点:
You could add a cast to for Action
, although it does get a bit LISP'y with all the parentheses:
M((Action)(() => throw new Exception()));
不理想,但是如果您想要最大的清晰度:
Not ideal, but if you want maximum clarity:
Action thrw = () => throw new Exception();
M(thrw);
这篇关于我怎样才能强制将throw用作语句而不是表达式(在lambda表达式中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!