How can it be that this == null?

前端 未结 1 396
难免孤独
难免孤独 2021-01-01 11:12

EDIT: This is not a duplicate of this question as this one is a practical example working with Delegate.CreateDelegate and the other one is a theoretical di

相关标签:
1条回答
  • 2021-01-01 12:09

    You can create this case using the Delegate.CreateDelegate overload where you provide a null reference for the target of invocation.

    class Foo
    {
        public void Method() 
        {
            Console.WriteLine(this == null);
        }
    }
    
    Action<Foo> action = (Action<Foo>)Delegate.CreateDelegate(
        typeof(Action<Foo>), 
        null, 
        typeof(Foo).GetMethod("Method"));
    
    action(null); //prints True
    

    From the MSDN remarks on that page:

    If firstArgument is a null reference and method is an instance method, the result depends on the signatures of the delegate type type and of method:

    •If the signature of type explicitly includes the hidden first parameter of method, the delegate is said to represent an open instance method. When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of method.

    •If the signatures of method and type match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do.

    So it's documented as a known, and probably intended, behaviour.

    0 讨论(0)
提交回复
热议问题