[英]LINQPad throws NullReferenceException on valid code
I'm reading about C# events and delegates , and I'd like to copy and paste the following code into LINQPad and run it: 我正在阅读有关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)
{
}
}
I am importing the System
namespace in Query Properties. 我在查询属性中导入
System
名称空间。
I can't figure out why LINQPad throws a NullReferenceException
: 我不知道为什么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
The same code compiles just fine if I create a project in Visual Studio, which is what I'd like to avoid. 如果我在Visual Studio中创建一个项目,则相同的代码可以很好地编译,这是我想要避免的。
You need to move your main method out of the class like this: 您需要像这样将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)
{
}
}
This is a limitation of LinqPad. 这是LinqPad的限制。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.