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

标签 c# .net

我一直认为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/

相关文章:

c# - 写入文件时出现奇怪的情况

c# - 使用表达式树生成排序列表

c# - 为什么 DwmGetWindowAttribute 与 DWMWA_EXTENDED_FRAME_BOUNDS 在切换监视器时表现异常?

c# - 查询语法错误,但查询正确

c# - 从 .NET 使用 infiniband 的最简单方法是什么?

C# 使用 .ToList() 将 IEnumerable 转换为 IList?

c# - 为什么我必须从 IDisposable 实现 Dispose,为什么不只是一个简单的释放方法...?

c# - 获取堆栈跟踪错误并且不明白为什么

c# - 字符串格式作为参数?

c# - 使用带有 XML 配置的 log4net 时没有日志文件