本文介绍了[BUG]使用Contract.Requires< T>在类的ctor中使用委托抛出NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重现的例子:

class Program
    {
        static void Main(string[] args)
        {
            var test = new Test("Haha", Guid.Empty);

        }
    }

    public class Test
    {
        private readonly int _id;

        public Test(string haha, Guid actionGuid)
        {
            Contract.Requires<ArgumentNullException>(haha != null);

            TestMethod(() => TestMethod(actionGuid));
        }

        private void TestMethod(Action action)
        {
            action();
        }

        private void TestMethod(Guid haha)
        {
            
        }
    }

在此示例中,输入参数"actionGuild"用于lambda表达式,paramater用于闭包。此代码的重写器生成无效语句。

In this example input parameter "actionGuild" is used in lambda expression and it paramater is closure. Rewriter for this code generate invalid statements.

反编译代码:

public class Test { private readonly int _id; public Test(string haha, Guid actionGuid) { __ContractsRuntime.Requires<ArgumentNullException>(haha != null, (string) null, "haha != null"); Action action1 = (Action) null; Test.\u003C\u003Ec__DisplayClass2 cDisplayClass2_1 = new Test.\u003C\u003Ec__DisplayClass2(); cDisplayClass2_1.actionGuid = actionGuid; base.\u002Ector(); cDisplayClass2_1.\u003C\u003E4__this = this; Test test = this; if (action1 == null) { // ISSUE: method pointer action1 = new Action((object) cDisplayClass2_1, __methodptr(\u003C\u002Ector\u003Eb__0)); } Action action2 = action1; test.TestMethod(action2);

Test.\\\c__DisplayClass2 cDisplayClass2_2;
cDisplayClass2_2.\\\4__this = this;

}

private void TestMethod(Action action)
{
action();
}

private void TestMethod(Guid haha​​)
{
}

[CompilerGenerated]
私人密封班\ u003C\\\>c__DisplayClass2
{
public Test \ u003C \ u003E4__this;
public Guid actionGuid;

public \\\c__DisplayClass2()
{
base.\\\.ctor();
}

public void \\\b__0()
{
this.\\\4__this.TestMethod(this.actionGuid) ;
}
}
}

Test.\u003C\u003Ec__DisplayClass2 cDisplayClass2_2; cDisplayClass2_2.\u003C\u003E4__this = this; } private void TestMethod(Action action) { action(); } private void TestMethod(Guid haha) { } [CompilerGenerated] private sealed class \u003C\u003Ec__DisplayClass2 { public Test \u003C\u003E4__this; public Guid actionGuid; public \u003C\u003Ec__DisplayClass2() { base.\u002Ector(); } public void \u003C\u002Ector\u003Eb__0() { this.\u003C\u003E4__this.TestMethod(this.actionGuid); } } }

推荐答案


这篇关于[BUG]使用Contract.Requires&lt; T&gt;在类的ctor中使用委托抛出NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:12