问题描述
修改:这是不是这个的副本作为这个人是一个实际的例子与Delegate.CreateDelegate工作,另一个是关于IL的理论讨论。没事做一与对方除了这个词和零。
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.
相对于此的 ...
我有一种情况,当一个事件处理程序被调用的实例,它是空。奇怪的。看图片:
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
从MSDN言论上页:
From the MSDN remarks on that page:
如果firstArgument是一个空引用和方法是一个实例方法,
结果取决于委托的签名类型类型和
法:
•如果type的签名明确包括方法隐藏的第一个
参数,委托据说代表一个开放的
实例方法。当调用委托,在
参数列表中的第一个参数传递给
方法的隐藏的实例参数。
•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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!