0

我有一个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 AClass BeMyEventArgsClass BOnMyEvent(e)

我可以创建一种由subscribesWrapperEventClass A处理程序引发的类型,但这似乎不优雅,我想知道是否有更清洁的方法来做到这一点?Class AClassB.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
    }
}
4

0 回答 0