假设有3个类A,B,C;假设B里面有个事件,这个事件是由A中的方法触发的,而该事件本身的发生又会导致C类中某个方法的发生,请问程序该怎么写?主要是涉及到3个类,感觉不太好写
不谈设计,只谈功能实现的话,可以如下这样:
class Program { static void Main(string[] args) { C c = new C(); B b = new B(); b.UnknownEvent += (ss, ee) => { Console.WriteLine("event is raised"); }; A a = new A(b, c); a.RaiseEvent(); Console.ReadKey(); } } public class A { private B _b; private C _c; public A(B b, C c) { this._b = b; this._c = c; } public void RaiseEvent() { Console.WriteLine("A raise B's event"); _b.OnUnknownEvent(); _c.Work(); } } public class B { public event EventHandler<EventArgs> UnknownEvent; public virtual void OnUnknownEvent() { if (UnknownEvent != null) { UnknownEvent(this, EventArgs.Empty); } } } public class C { public void Work() { Console.WriteLine("C is working"); } }
这样?
public class A { private B b = new B(); public A() { b.事件B += B事件; } public void B事件() { C c = new C(); c.C方法(); } } public class B { public event Action 事件B; } public class C { public void C方法() { } }
事件委托 delegate 去了解下