Forwarding Events of Different Type

2020-05-06 08:56发布

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条回答
啃猪蹄的小仙女
2楼-- · 2020-05-06 09:20

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];
        }
    }
}
查看更多
登录 后发表回答