怎么可能这个== null? [英] How can it be that this == null?

查看:131
本文介绍了怎么可能这个== null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:这与此重载,您提供一个 null 调用目标的引用。

  class Foo 
{
public void Method()
{
Console.WriteLine(this == null);
}
}

动作< Foo> action =(Action&Foo>)Delegate.CreateDelegate(
typeof(Action&Foo>),
null,
typeof(Foo).GetMethod(Method));

动作(null); //打印True






从MSDN的评论页面:


如果firstArgument是一个空引用,方法是一个实例方法,
结果取决于代理的签名类型类型和
方法:



•如果类型的签名显式包含方法的隐藏的第一个
参数,则代表表示一个打开的
实例方法。当委托被调用时,
参数列表中的第一个参数被传递给
方法的隐藏实例参数。



•如果签名的方法和类型匹配(即,所有参数
类型都是兼容的),那么委托被认为是关闭一个
的空引用。调用代理就像在null实例上调用一个实例
方法,这对
做不是特别有用的。


所以它被记录为已知的,可能是 行为。


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???

解决方案

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.

这篇关于怎么可能这个== null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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