扩展方法的空目标 [英] null target of extension method

查看:131
本文介绍了扩展方法的空目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static IFoo Bar<T>(this IFoo target, ...)
{
   // I'm curious about how useful this check is.
   if (target == null) throw new ArgumentNullException("target");

   ...
}



(1)代码因为我觉得在任何情况下,调用代码将是一个检查上述觉得奇怪,我。有一些细微之处,以扩展方法在这方面的应用?

(1) The code above seems strange to me because I feel like in any case the calling code would be the one to check that. Is there some subtlety to extension methods in this area that applies?

(2)是否有利用的事实,目标可以是空合法的格局?请问这是奇怪,为什么对空引用调用扩展方法不会生成运行时异常的方法一样,如果你叫上一个空引用实例方法的结果。

(2) Is there a legitimate pattern that leverages the fact that the target can be null? I ask this as a consequence of wondering why calling an extension method on a null reference wouldn't generate the runtime exception the same way as if you called an instance method on a null reference.

推荐答案

考虑到空可以是一个参数的方法。此外还应考虑到扩展方法 foo.Bar< INT>(); IFooExtensions.Bar<真的只是语法糖; INT>(富); ,你会看到,是的,争论的确可以为空,因此,如果你正在做的事情的说法,这可能确实是适当的测试为空(或者干脆让的NullReferenceException 被抛出,你挑)。

Consider that null can be an argument to a method. Consider also that the extension method foo.Bar<int>(); is really just syntactic sugar for IFooExtensions.Bar<int>(foo); and you will see that, yes, the argument can indeed be null so if you're doing something with the argument, it may certainly be appropriate to test it for null (or simply let a NullReferenceException be thrown, take your pick).

注意:将不只是通过的调用的它与一个空引用的对象,因为记住,该方法实际上并不属于得到一个异常物体。你只得到了异常,如果(a)您有意自己或(b)方法体实际上是想用那是空的情况下工作导致它扔之一。

Note: You would not get an exception merely by calling it with a null referenced object, because remember that the method does not actually belong to the object. You only get the exception if (a) you purposefully throw one yourself or (b) the method body actually causes it by trying to work with the instance that is null.

这篇关于扩展方法的空目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆