null target of extension method

别说谁变了你拦得住时间么 提交于 2019-12-12 13:38:37

问题


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) 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) 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.


回答1:


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).

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.




回答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.

Well, here's one use of it.

public static class UtilityExtensions
{
    public static void ThrowIfNull( this object obj, string argName )
    {
        if ( obj == null )
        {
            throw new ArgumentNullException( argName );
        }
    }
}

Now you can write null checks easily and on one line (helpful if your coding convention forces you to use braces with all if statements).

public void Foo(string bar)
{
    bar.ThrowIfNull("bar");
    // ...
}

Whether or not you consider that a "legitimate" pattern is up to you, but I'd be very sad if the runtime was changed to make extension method invocations on null references throw exceptions.




回答3:


Since extension methods really are only syntactic sugar for calling a static method with the object as the first parameter, I don't see why null for this parameter value shouldn't be allowed.



来源:https://stackoverflow.com/questions/3895032/null-target-of-extension-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!