加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么这样工作?执行方法从IL没有实例

发布时间:2020-12-15 04:11:00 所属栏目:百科 来源:网络整理
导读:我正在看着 What’s the strangest corner case you’ve seen in C# or .NET? ,这段代码让我想了一下: public class Program{ delegate void HelloDelegate(Strange bar); [STAThread()] public static void Main(string[] args) { Strange bar = null; var
我正在看着 What’s the strangest corner case you’ve seen in C# or .NET?,这段代码让我想了一下:
public class Program
{
    delegate void HelloDelegate(Strange bar);

    [STAThread()]
    public static void Main(string[] args)
    {
        Strange bar = null;
        var hello = new DynamicMethod("ThisIsNull",typeof(void),new[] { typeof(Strange) },typeof(Strange).Module);
        ILGenerator il = hello.GetILGenerator(256);
        il.Emit(OpCodes.Ldarg_0);
        var foo = typeof(Strange).GetMethod("Foo");
        il.Emit(OpCodes.Call,foo);
        il.Emit(OpCodes.Ret);
        var print = (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));
        print(bar);
        Console.ReadLine();
    }

    internal sealed class Strange
    {
       public void Foo()
       {
           Console.WriteLine(this == null);
       }
    }
}

我明白代码的作用,但我不明白为什么它的作品.不是那样做null.Foo()?它的作用就好像Foo()是静态的,而这正在被调用:Strange.Foo();.

请你告诉我我失踪了什么

解决方法

这是作为正常参数实现的;你的代码只是作为这个参数传递null.

通常会抛出NullReferenceException的唯一原因是方法通常使用CallVirt指令调用,该指令对此参数执行vtable查找,如果为空,则抛出.

如果您使用调用,即使该方法为空,该方法也将执行得很好,尽管该方法本身可能会在以后抛出.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读