我是reading about C# events and delegates,我想将以下代码复制并粘贴到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中创建一个项目,那么相同的代码编译就好了,这是我想要避免的。
答案 0 :(得分:3)
您需要将主要方法移出类,如下所示:
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的限制。
干杯