转发不同类型的事件

时间:2014-06-23 16:46:42

标签: c# events event-handling

我试图将事件从一个类转发到其中包含的对象(如下所述: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}}

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