通知何时触发另一个类的事件

时间:2012-12-13 09:33:38

标签: c# events event-handling

我有

class A
{
    B b;

    //call this Method when b.Button_click or b.someMethod is launched
    private void MyMethod()
    {            
    }

    ??
}

Class B
{
    //here i.e. a button is pressed and in Class A 
    //i want to call also MyMethod() in Class A after the button is pressed 
    private void Button_Click(object o, EventArgs s)
    {
         SomeMethod();
    }

    public void SomeMethod()
    {           
    }

    ??
}

A类有一个B类实例。

如何做到这一点?

3 个答案:

答案 0 :(得分:44)

您需要在“B”类声明一个公共事件 - 并让“A”类订阅它:

这样的事情:

class B
{
    //A public event for listeners to subscribe to
    public event EventHandler SomethingHappened;

    private void Button_Click(object o, EventArgs s)
    {
        //Fire the event - notifying all subscribers
        if(SomethingHappened != null)
            SomethingHappened(this, null);
    }
....

class A
{
    //Where B is used - subscribe to it's public event
    public A()
    {
        B objectToSubscribeTo = new B();
        objectToSubscribeTo.SomethingHappened += HandleSomethingHappening;
    }

    public void HandleSomethingHappening(object sender, EventArgs e)
    {
        //Do something here
    }

....

答案 1 :(得分:6)

你需要三件事(在代码中用注释标记):

  1. 在B级声明event
  2. 发生事件时在B类中引发事件(在您的情况下 - 执行Button_Click事件处理程序)。请记住,您需要验证是否存在任何订户。否则,你会在举起事件时得到NullReferenceException。
  3. 订阅B类事件。您需要拥有B类实例,甚至您想要订阅(另一个选项 - 静态事件,但这些事件将由B类的所有实例引发)。
  4. 代码:

    class A
    {
        B b;
    
        public A(B b)
        {
            this.b = b;
            // subscribe to event
            b.SomethingHappened += MyMethod;
        }
    
        private void MyMethod() { }
    }
    
    class B
    {
        // declare event
        public event Action SomethingHappened;
    
        private void Button_Click(object o, EventArgs s)
        {
             // raise event
             if (SomethingHappened != null)
                 SomethingHappened();
    
             SomeMethod();
        }
    
        public void SomeMethod() { }
    }
    

答案 2 :(得分:0)

相关问题