2014-09-11 137 views
-1

我不確定這是否是正確的標題,但我會解釋。 我有兩個類,TestBoo,由我自己編寫。第三類叫Manager也在那裏。我想啓動一個Manager對象,然後監聽類Test中方法的更改。事件偵聽通知其他事件

public class Test 
{ 
    Manager manager; 
    public event EventHandler NotifyMe; 

    public Test() 
    { 
     manager = new Manager(); 
    } 

    public void start() 
    { 
     manager.ChangedState += (sender, e) => 
     { 
      Console.WriteLine(e.State); 
      NotifyMe(this, e); 
     } 
    } 
} 

然後我有類Boo與方法foo()當我要聽我的NotifyMe事件,最終得到如果manager對象已經解僱了ChangedState

public class Boo 
{ 
    public void foo() 
    { 
     Test test = new Test(); 
     test.start(); 

     test.NotifyMe += (sender, e) => 
     { 
      Console.WriteLine("Manager has changed the state"); 
     } 
    } 
} 

這僅是第一次,當我執行start()和我的想法是監聽的manager.ChangedState通過test.NotifyMe所有的時間。這是要走的路嗎?

+1

你需要在調用start之前連接你的事件處理程序(test.NotifyMe)嗎? – 2014-09-11 11:44:21

回答

0

我認爲你的問題是test是一個局部變量。只要foo退出,它引用的對象就有資格進行垃圾回收;一旦該對象被垃圾收集,它將不再寫入控制檯。試試這個:

public class Boo 
{ 
    private readonly Test _test = new Test(); 

    public void foo() 
    { 
     _test.start(); 

     _test.NotifyMe += (sender, e) => 
     { 
      Console.WriteLine("Manager has changed the state"); 
     } 
    } 
}