我试图将事件从一个类转发到其中包含的对象(如下所述:Forwarding events in C#)。但是,事件的类型不同。
例如,我有一个类Item
,它公开ValueChanged
类型EventHandler
的事件处理程序。课程ItemHaver
会公开EventHandler<StatusEventArgs>
,Item.ValueChanged
会在add/remove
时触发,但也应提供其他信息。如何正确实施ItemValueChanged
事件声明的add
?
在下面的代码中,remove
方法中的lambda函数是否会执行正确的操作,如果是,那么处理class Item
{
public event EventHandler ValueChanged;
}
class ItemHaver
{
private int _status;
private Item _item;
public event EventHandler<StatusEventArgs> ItemValueChanged
{
add
{
_item.ValueChanged += value; // Wrong type
_item.ValueChanged +=
(obj, e) => value(obj, new StatusEventArgs(this._status));
}
remove
{
_item.ValueChanged -= // Does this even work?
(obj, e) => value(obj, new StatusEventArgs(this._status));
}
}
}
class StatusEventArgs : EventArgs
{
int Status { get; private set; }
StatusEventArgs(int status) { Status = status; }
}
的正确方法是什么?
{{1}}
答案 0 :(得分:2)
我尝试使用字典来处理处理程序。
class ItemHaver
{
private int _status;
private Item _item;
private Dictionary<EventHandler<StatusEventArgs>, EventHandler> handlersMap = new Dictionary<EventHandler<StatusEventArgs>, EventHandler>();
public event EventHandler<StatusEventArgs> ItemValueChanged
{
add
{
// _item.ValueChanged += value; // Wrong type
handlersMap.Add(value, (obj, e) => value(obj, new StatusEventArgs(this._status)));
_item.ValueChanged += handlersMap[value];
}
remove
{
_item.ValueChanged -= handlersMap[value];
}
}
}