How can it be that this == null?

2019-02-07 19:06发布

问题:

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 discussion about IL. Nothing to do one with each other besides the words this and null.

Relative to this question ...

I have a situation when an event handler is called on an instance that is null. Weird. Look at the image:

I do not understand what is happening. How an instance method can be called on a null instance???

回答1:

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.