我曾经使用过以下内容:
public event EventHandler OnComplete = delegate { };
我不确定,这是怎么调用的,这是一个“事件默认初始化器”??
但问题似乎是当我从EventArgs派生时,创建了我自己的EventHandler并决定使用相同的方法。请看:
public class MyEventArgs : EventArgs
{
int result;
public int Result
{
get
{
if (exceptionObject == null)
return result;
else
throw new InvalidOperationException();
}
internal set { result = value; }
}
Exception exceptionObject;
public Exception ExceptionObject
{
get { return exceptionObject; }
internal set { exceptionObject = value; }
}
}
public delegate EventHandler MyEventHandler(object sender, MyEventArgs e);
public class MyOperation
{
public event MyEventHandler OnOperationComplete = delegate { };
}
所以,行
public event MyEventHandler OnOperationComplete = delegate { };
导致问题。
如何为“我的”事件进行正确的默认初始化?
答案 0 :(得分:4)
public event MyEventHandler OnOperationComplete = (sender, args) => { return null; };
我也认为你的意思是:
public delegate void MyEventHandler(object sender, MyEventArgs e);
不是
public delegate EventHandler MyEventHandler(object sender, MyEventArgs e);