我试图将事件从一个类转发到包含在其中的对象(如这里所述:c#中的转发事件)。然而,事件的类型是不同的。
例如,我有一个类Item
,它公开EventHandler
类型的ValueChanged
事件处理程序。类ItemHaver
公开了一个EventHandler<StatusEventArgs>
,它应该在Item.ValueChanged
触发时触发,但也应该提供额外的信息。我如何正确地实现add/remove
到ItemValueChanged
事件声明?
在下面的代码中,add
方法中的lambda函数是否执行正确的操作,如果是,处理remove
的正确方法是什么?
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; }
}
我会尝试使用字典来映射处理程序。
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];
}
}
}