繁体   English   中英

LINQPad在有效代码上引发NullReferenceException

[英]LINQPad throws NullReferenceException on valid code

我正在阅读有关C#事件和委托的信息 ,我想将以下代码复制并粘贴到LINQPad中并运行它:

class Test
{
    public event EventHandler MyEvent
    {
        add
        {
            Console.WriteLine ("add operation");
        }

        remove
        {
            Console.WriteLine ("remove operation");
        }
    }

    static void Main()
    {
        Test t = new Test();

        t.MyEvent += new EventHandler (t.DoNothing);
        t.MyEvent -= null;
    }

    void DoNothing (object sender, EventArgs e)
    {
    }
}

我在查询属性中导入System名称空间。

我不知道为什么LINQPad抛出NullReferenceException

Message Object reference not set to an instance of an object.
Data    Data
InnerException  (null)
TargetSite  TargetSite
StackTrace     at LINQPad.ExecutionModel.ClrQueryRunner.Run()
   at LINQPad.ExecutionModel.Server.RunQuery(QueryRunner runner)
HelpLink    null
Source  LINQPad
HResult -2147467261

如果我在Visual Studio中创建一个项目,则相同的代码可以很好地编译,这是我想要避免的。

您需要像这样将main方法移出类:

void Main()
{
    Test t = new Test();

    t.MyEvent += new EventHandler (t.DoNothing);
    t.MyEvent -= null;
}

class Test
{
    public event EventHandler MyEvent
    {
        add
        {
            Console.WriteLine ("add operation");
        }

        remove
        {
            Console.WriteLine ("remove operation");
        }
    }

    public void DoNothing (object sender, EventArgs e)
    {
    }
}

这是LinqPad的限制。

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM