2014-06-23 28 views
0

我試圖將事件從一個類轉發到其中包含的對象(如此處所述:Forwarding events in C#)。但是,這些事件是不同類型的。轉發不同類型的事件

例如,我有一個類Item,它揭示類型EventHandler類型的事件處理程序。類ItemHaver公開EventHandler<StatusEventArgs>,應該在Item.ValueChanged時觸發,但也應提供其他信息。如何正確執行add/removeItemValueChanged事件聲明?

在下面的代碼中,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; } 
} 

回答

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

謝謝,這似乎工作。我實際上進行了更深層次的重構,並且改變了'Item'類的底層EventHandler以符合預期的結果(實際的代碼涉及到很多不同類型的'Item',所有這些都是在泛型之前在C#中開發的,無論如何,不要評論你的方法的效率,但它確實可以作爲一個臨時的解決方案。 –