Forwarding Events of Different Type

别来无恙 提交于 2019-12-31 07:01:19

问题


I'm trying to forward events from one class to objects contained within it (as described here: Forwarding events in C#). However, the events are of different type.

For example, I have a class Item which exposes a ValueChanged event handler of type EventHandler. The class ItemHaver exposes an EventHandler<StatusEventArgs>, which should fire whenever Item.ValueChanged does, but should also provide additional information. How do I properly implement add/remove to the ItemValueChanged event declaration?

In the below code, would the lambda function in the add method perform the correct action, and if so, what's the proper way to handle the 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; }
}

回答1:


I'd try using a dictionary in which I map the handlers.

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


来源:https://stackoverflow.com/questions/24371159/forwarding-events-of-different-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!