2014-09-11 140 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"); 
     } 
    } 
}