c# - this == null 怎么可能?

标签 c# .net events null

编辑:这不是 question 的副本因为这是一个使用 Delegate.CreateDelegate 的实际示例,另一个是关于 IL 的理论讨论。除了 this 和 null 这两个词之外,彼此没有任何关系。

相对于此question ...

我有一种情况,当一个事件处理程序在一个空的实例上被调用时。诡异的。看图:

enter image description here

我不明白发生了什么。如何在空实例上调用实例方法???

最佳答案

您可以使用 Delegate.CreateDelegate 创建此案例为调用目标提供 null 引用的重载。

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

来自该页面上的 MSDN 评论:

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.

因此它被记录为已知的,并且可能是有意的行为。

关于c# - this == null 怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675720/

相关文章:

.net - App.config dllmap 条目可移植性

c# - 将一个字符串与多个不同的字符串进行比较

javascript - Ajax 未附加到我的下拉列表(C# MVC)

c# - 元组到元组的转换

c# - 覆盖的扩展方法需要程序集引用

c# - 为什么我们指定一个委托(delegate)和一个事件,为什么不在 C# 中使用一个事件?

c# - 如何在线程之间传递锁?

c# - Selenium C# 中的 headless (headless) Firefox

JavaScript:获取调用 HTML 对象的函数

apache-flex - 如何从 SWFLoader 中的 SWF 向父 Flex 应用程序引发事件?