gpt4 book ai didi

c# - .NET 实例方法中的 this == null - 为什么这可能?

转载 作者:IT王子 更新时间:2023-10-29 04:05:00 24 4
gpt4 key购买 nike

我一直认为this在实例方法体内是不可能为null的。下面的简单程序演示了这是可能的。这是一些记录在案的行为吗?

class Foo
{
public void Bar()
{
Debug.Assert(this == null);
}
}

public static void Test()
{
var action = (Action)Delegate.CreateDelegate(typeof (Action), null, typeof(Foo).GetMethod("Bar"));
action();
}

更新

我同意这个方法的记录方式的回答。但是,我真的不明白这种行为。特别是因为这不是 C# 的设计方式。

We had gotten a report from somebody (likely one of the .NET groups using C# (thought it wasn't yet named C# at that time)) who had written code that called a method on a null pointer, but they didn’t get an exception because the method didn’t access any fields (ie “this” was null, but nothing in the method used it). That method then called another method which did use the this point and threw an exception, and a bit of head-scratching ensued. After they figured it out, they sent us a note about it. We thought that being able to call a method on a null instance was a bit weird. Peter Golde did some testing to see what the perf impact was of always using callvirt, and it was small enough that we decided to make the change.

http://blogs.msdn.com/b/ericgu/archive/2008/07/02/why-does-c-always-use-callvirt.aspx

最佳答案

因为您将 null 传递到 Delegate.CreateDelegatefirstArgument

所以你在空对象上调用实例方法。

http://msdn.microsoft.com/en-us/library/74x8f551.aspx

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# - .NET 实例方法中的 this == null - 为什么这可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625326/

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