10

我有

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 类的一个实例。

如何才能做到这一点?

4

3 回答 3

64

您需要在“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
    }

....
于 2012-12-13T09:40:49.680 回答
8

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

  1. 在 B 类中声明事件
  2. 发生某些事情时在 B 类中引发事件(在您的情况下 - 执行了 Button_Click 事件处理程序)。请记住,您需要验证是否存在任何订阅者。否则,您将在引发事件时获得 NullReferenceException。
  3. 订阅 B 类的事件。您需要拥有 B 类的实例,即使您也想订阅(另一种选择 - 静态事件,但这些事件将由 B 类的所有实例引发)。

代码:

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() { }
}
于 2012-12-13T09:41:16.710 回答
-1

看看从 B 类中引发事件

看一下

引发事件

处理和引发事件

如何:引发和使用事件

于 2012-12-13T09:36:32.113 回答