Notify when event from another class is triggered [duplicate]

江枫思渺然 提交于 2019-11-27 12:07:16

问题


I have

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()
    {           
    }

    ??
}

Class A has a instance of Class B.

How can this be done?


回答1:


You'll need to declare a public event on class 'B' - and have class 'A' subscribe to it:

Something like this:

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
    }

....



回答2:


You need three things (which is marked by comments in code):

  1. Declare event in class B
  2. Raise event in class B when something happened (in your case - Button_Click event handler executed). Keep in mind that you need to verify if there are any subscribers exists. Otherwise you will get NullReferenceException on raising event.
  3. Subscribe to event of class B. You need to have instance of class B, which even you want to subscribe (another option - static events, but those events will be raised by all instances of class B).

Code:

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() { }
}



回答3:


Have a look at rasing an event from Class B

Have a look at

Raising an Event

Handling and Raising Events

How to: Raise and Consume Events



来源:https://stackoverflow.com/questions/13856869/notify-when-event-from-another-class-is-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!