gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:16:49 25 4
gpt4 key购买 nike

编辑:这不是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com