Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 触发另一个类的事件时通知_C#_Events_Event Handling - Fatal编程技术网

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

C# 触发另一个类的事件时通知,c#,events,event-handling,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 MyMet

我有

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的实例


如何做到这一点?

看一下从B类中删除事件

看看


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

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

  • B类申报
  • 发生事件时在类B中引发事件(在您的示例中,是-按钮\单击事件处理程序已执行)。请记住,您需要验证是否存在任何订户。否则,您将在引发事件时获得NullReferenceException
  • 订阅类B的事件。您需要有类B的实例,即使您想要订阅(另一个选项-静态事件,但这些事件将由类B的所有实例引发)
  • 代码:


    Thx伙计们,所有答案+1到allDunno为什么要搜索一个C#event示例如此清晰和简单,只是为了交流两个类?经过几个小时的搜索终于。。。我想哭,非常感谢。@Konayuki:非常同意。我一直在寻找一个简单的例子,就是这样。(at)DaveBish:干得好——简单有效。
    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() { }
    }