我有一个MyEvent
定义的事件Class B
和一个事件处理程序的委托,如MyEventHandler(object sender, MyEventArgs e)
.
我的应用程序有几个实例Class A
,每个Class A
实例都有一个成员实例Class B
。
如果Class A
订阅了一个处理程序,ClassB.MyEvent
那么sender
将是Class B
引发事件的实例,并且e
将是MyEventArgs
来自对 的Class B
调用OnMyEvent(e)
。
但是 - 我真正想要的是让应用程序订阅一个处理程序ClassA.ClassB.MyEvent
(或ClassA.ClassBMyEvent
在适当的情况下),它sender
表示具有引发事件的实例的实例,并且仍然是来自对.Class A
Class B
e
MyEventArgs
Class B
OnMyEvent(e)
我可以创建一种由subscribesWrapperEvent
的Class A
处理程序引发的类型,但这似乎不优雅,我想知道是否有更清洁的方法来做到这一点?Class A
ClassB.MyEvent
每个请求的代码片段:
public class ClassB
{
public event MyEventHandler MyEvent;
public delegate void MyEventHandler(object sender, MyEventArgs e);
public class MyEventArgs : EventArgs
{
public MyEventArgs()
{ }
}
private virtual void OnMyEvent(MyEventArgs e)
{
MyEventHandler handler = MyEvent;
if (handler != null)
{
handler(this, e);
}
}
public ClassB()
{
/// do stuff
}
public void Method()
{
OnMyEvent(new MyEventArgs());
}
}
public class ClassA
{
private ClassB member = new ClassB();
public ClassA()
{
/// do stuff
}
public void Method()
{
member.Method();
}
}
static class Program
{
static List<ClassA> aList = new List<ClassA>();
static void Main()
{
aList.Add(new ClassA());
/// I would like to be able to do this...
aList[0].MyEvent += MyEvent_handler;
aList[0].Method();
}
void MyEvent_handler(object sender, ClassB.MyEventArgs e)
{
/// ... such that sender is the ClassA instance i.e. aList[0]
/// and e is the MyEventArgs passed to OnMyEvent in ClassB
}
}