将事件从C类通过B类传递到A类 [英] Pass event from class C through class B to class A
问题描述
我有A类,它实现了B类的大量实例.B类封装了C类的一个实例.
I have Class A which implements a large number of instances of Class B. Class B encapsulates an instance of Class C.
Class引发需要由A类处理的事件.A类不需要了解C类.C类正在传回基于性能的统计信息,然后A需要合并这些统计信息.
Class raises events which need to be handled by Class A. Class A does not need to know about Class C. Class C is passing back performance based statistics which A then needs to coalesce.
如何在B类中创建事件并进行连接,以便A类可以订阅B类的事件并从C类接收事件?
How do I create the events in Class B and connect them so that Class A can subscribe to Class B's events and receive the events from Class C?
推荐答案
事件不过是一对包装委托字段的方法.您可以覆盖add&的默认实现.删除 ClassB
中的方法以将值直接传递给 ClassC
中的事件:
An event is nothing more than a pair of methods wrapping a delegate field. You can override the default implementation of the add & remove methods in ClassB
to pass the value straight to the event in ClassC
:
public class ClassB
{
private ClassC m_C = new ClassC();
public event EventHandler MyEvent
{
add { m_C.MyEvent += value; }
remove { m_C.MyEvent -= value; }
}
}
这篇关于将事件从C类通过B类传递到A类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!