使用空合并运算符进行抛出的语法糖
假设如果我们尝试将 null 分配给某些东西,我们想要抛出异常,那么这个技巧怎么样:
public static class ExceptionExtension
{
public static T Throw<T>(this Exception exc)
{
throw exc;
}
}
我们可以像这样使用:
return possibleNull ?? new Exception("Unspecified something....").Throw<string>();
你认为这是一个好/最差/无用的做法吗?
Let's suppose we want to throw if we try to assign null to something, what about this trick:
public static class ExceptionExtension
{
public static T Throw<T>(this Exception exc)
{
throw exc;
}
}
that we can use for example like this:
return possibleNull ?? new Exception("Unspecified something....").Throw<string>();
do you think it is a good/worst/useless practice ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这对我来说毫无意义——可读性不强。我希望
??
运算符的第二个参数是相同类型的possibleNull
,而不是抛出异常。我更愿意看到:
It makes no sense to me - not very readable. I would expect the second argument of the
??
operator to be of the same type ofpossibleNull
, not to throw an excpetion.I would much rather see:
创建某种抛出异常的静态帮助器类可能会更好、更具可读性
像这样
It could be better and more readable to create some kind of static helper class that throws
Like this
您始终可以将其放在某种短名称的静态帮助器类中:
您的其他示例没有多大意义,我选择将其称为“无用”实践。
向帮助器类添加一点“流畅性”往往会侧重于使内容更具可读性。
http://en.wikipedia.org/wiki/Fluent_interface
You could always stick it in some sort of short-named static helper class:
Your other example wouldn't make much sense, I'd opt for calling it "useless" practice.
Adding a bit of "fluency" to helper classes tends to focus on making things more readable.
http://en.wikipedia.org/wiki/Fluent_interface
我不认为这是一个好的做法。
首先,扩展方法本身只是为我们已经有关键字的东西引入了一个方法:抛出。这可能会令人困惑。它声明了一个返回类型,尽管它永远不会返回值,只是为了让编译器在您想要使用它的上下文中取悦。参考其他人已经指出的,这是一个“最令人惊讶的原则”。
然后,看看如何使用此方法,生成的代码似乎不太清晰可读。更糟糕的是:您只能在表达式中使用这种方法,因此您总是会得到以某种方式使用对象的代码(在您的示例中:只需返回它)并在同一行中检查它是否为 null 作为副作用。我更喜欢明确地进行空检查,而不是与其他东西混合。像 CuttingEdge.Conditions 这样的库可以帮助减少您为此键入的代码量。您可以在示例中以这种方式使用它
I wouldn't consider it a good practice.
First, the extension method itself just introduces a method for something we already have a keyword for: throw. This might be confusing. It declares a return type though it will never return a value, just to please the compiler in the context where you want to use it. Referring to what others already pointed out, that's rather a "principle of most astonishment".
Then, looking on how you would employ this method, the resulting code seems not very clear to read. Even worse: you can only use this approach in an expression, so you would always end up with code that uses an object in some way (in your example: just return it) and checks it for null as a side effect in the same line. I'd prefer doing null checks explicitly and not mixed with something else. A library like CuttingEdge.Conditions can help to reduce the amount of code you have to type for this. You would use it in your example this way