环境:MS SQL Server、EF、WCF-RIA-Service、Sliverlight
尝试为异步调用完成事件定义一个事件,例如:
public event EventHandler<int> MySaveComplete;
这个事件是调用DB中的一个SP,返回一个ID值(int)。
但在尝试编译代码时收到错误消息:
The type 'int' cannot be used as type parameter 'TEventArgs' in the generic type or method 'System.EventHandler'. There is no boxing conversion from 'int' to 'System.EventArgs'
如何解决这个问题?
最佳答案
EventHandler<T>
要求通用参数的类型为 EventArgs
(即从它继承的)。因此,您应该创建自己的类:
public class MySaveCompleteEventArgs : EventArgs
{
public MySaveCompleteEventArgs(int id)
{
ID = id;
}
public int ID { get; private set; }
}
并将其用作 EventHandler<T>
参数:
public event EventHandler<MySaveCompleteEventArgs> MySaveComplete;
事件引发:
protected void OnMySaveComplete(int id)
{
if (MySaveComplete == null)
return;
MySaveComplete(this, new MySaveCompleteEventArgs(id));
}
您也可以使用 Action<int>
委托(delegate)为事件类型。
关于c# - 如何捕获事件处理程序的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318925/