Forwarding Events of Different Type

前端 未结 1 1499
时光说笑
时光说笑 2021-01-26 08:44

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

相关标签:
1条回答
  • 2021-01-26 09:15

    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];
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题