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

Gob*_*ins 6 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()
    {           
    }

    ??
}
Run Code Online (Sandbox Code Playgroud)

A类有一个B类实例.

如何才能做到这一点?

Dav*_*ish 46

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

....
Run Code Online (Sandbox Code Playgroud)

  • Dunno为什么要搜索C#事件示例如此简单,如此简单,只是为了传达两个类?经过几个小时的搜索终于......我想哭,非常感谢你. (10认同)
  • @Konayuki:不能完全同意。我一直在寻找一个简单的例子,就是这样。(at)DaveBish:做得好-简单有效。 (2认同)

Ser*_*kiy 7

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

  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() { }
}
Run Code Online (Sandbox Code Playgroud)