2

我曾经使用以下内容:

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 { };

导致问题。

如何为“我的”事件进行正确的默认初始化?

4

1 回答 1

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);
于 2012-07-27T03:02:29.947 回答