关于扩展方法
当对 null 调用扩展方法时,我是否总是需要抛出 ArgumentNullException
? (Enumerable
中的扩展方法抛出 ArgumentNullException
。)我想对此进行澄清。如果答案都是“是”和“否”,请同时列出两种情况。
Shall I always need to throw ArgumentNullException
when an extension method is called on null? (Extension methods in Enumerable
throw ArgumentNullException
.) I would like to have clarification on this. If the answer is both "Yes" and "No" please present both the cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果参数为
null
并且您不支持该条件,则需要抛出它。如果这不是问题,则无需抛出异常。人们可能期望在大多数情况下,this
参数的空参数将是一种不支持的条件,但绝不是总是这种情况。扩展方法中抛出此异常(以及 null 检查)的需要与传统方法中没有什么不同。
You need to throw it if the argument is
null
and you don't support that condition. If that isn't a problem, there's no need to throw the exception. One might expect in most cases that a null argument for thethis
argument would be an unsupportable condition, but by no means is that always the case.The need for throwing this exception (and for null checking) is no different in extension methods than in traditional methods.
我见过这种类型的方法经常被定义为扩展方法:
并像这样使用:
因此,在这种特殊情况下,如果参数为空,则抛出异常是没有意义的。扩展方法与任何其他方法没有什么不同,只是语法更奇特。
I've seen this kinds of methods defined often as extension methods:
and used like:
So, in this special case, it makes no sense to throw if the argument is null. Extension methods are not different from any other methods, just the syntax is fancier.