2014-04-29 22 views
1

我正在嘗試編寫一個抽象類,它包含公共應用程序的多個組件的數據,並提供這些組件通知其他組件的能力,他們正在處理的數據改變。不幸的是,其他組件都沒有提取正在觸發的事件。我決定寫一個快速測試,看看我是否可以明確哪些是錯誤的,但我遇到了完全相同的問題。我誤解事件如何運作?還是我錯過了明顯的東西?僅通過類的單個實例檢測到的事件

void Main() 
{ 
    EventHandler<string> EVENT = delegate {}; 
    var test = new DerivedClass("test", ref EVENT, 6); 
    var test2 = new DerivedClass("test2", ref EVENT, 8); 
    test.Number = 7; 
    test2.Number = 4; 
} 

public class DerivedClass : BaseClass 
{ 
    protected override void OnChanged(object sender, string e) 
    { 
     Console.WriteLine(string.Format("Derived class event fired from {0}! New value is {1}", sender, e)); 
    } 

    public DerivedClass(string name, ref EventHandler<string> handler, int val) : base(ref handler, val) 
    { 
     this._name = _name; 
    } 

    public override string ToString() 
    { 
     return _name; 
    } 
    string _name; 
} 

public abstract class BaseClass 
{ 
    public virtual int Number 
    { 
     get { return _number; } 
     set 
     { 
      _handler(this, value); 
      _number = value; 
     } 
    } 

    protected virtual void OnChanged(object sender, string e) 
    { 
     Console.WriteLine("Base class event fired! " + e); 
    } 

    protected BaseClass(ref EventHandler<string> handler, int val) 
    { 
     _number = val; 
     _handler = handler; 
     if (_handler != null) _handler += this.OnChanged; 
    } 

    protected event EventHandler<string> _handler; 
    protected int _number; 

    public override string ToString() 
    { 
     return "A BaseClass"; 
    } 
} 

輸出:

Derived class event fired from test! New value is 7 
Derived class event fired from test2! New value is 4 
+0

我看不出有什麼問題,它看起來像你的輸出完全符合你的代碼。你期望它做什麼?順便說一下,像這樣傳遞和分配事件並不是標準的C#事件練習,你總是使用+ =(=可以用來清除多播委託,但通常不鼓勵) – BradleyDotNET

+0

我期望事件觸發兩個DerivedClasses。雖然創建一個靜態事件起作用。 – Otaia

回答

0

我誤解的事件是如何工作的?

也許。具體來說,您似乎在印象中是以事件按類爲基礎來處理,或者子類實例將全部共享相同的父類實例。

你宣佈你的活動,爲非static

protected event EventHandler<string> _handler; 

所以擴展此類都會有自己的這一事件的實例的任何類的每個實例。根據你想要完成的事情,你可能會考慮使事件成爲靜態的?