WinForm event subscription to another class

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

public partial class Form1 : Form {     private EventThrower _Thrower;      public Form1()     {         InitializeComponent();     }      private void DoSomething()     {         MessageBox.Show("It worked");     }      private void button1_Click(object sender, EventArgs e)     {         _Thrower = new EventThrower();         //using lambda expression..need to use .NET2 so can't use this.         _Thrower.ThrowEvent += (sender2, args) => { DoSomething(); };          var eventThrower = new EventThrower();         eventThrower.test();     } }  public class EventThrower {     public delegate void EventHandler(object sender, EventArgs args);     public event EventHandler ThrowEvent = delegate { };      public void SomethingHappened()     {         ThrowEvent(this, new EventArgs());     }      public void test()     {         System.Threading.Thread.Sleep(1000);         SomethingHappened();     } } 

I'm trying to get my winform UI to subscribe to an event in EventThrower class. DoSomething never fires.

How to subscribe to other class' events in c#?

回答1:

This is because you create a new EventThrower before calling test.

If you change:

    var eventThrower = new EventThrower();     eventThrower.test(); 

to:

    _Thrower.test(); 

It will call DoSomething.



回答2:

The event is not static, one instance of the EventHandler exists for each instance of EventThrower.

You subscribe to the event on _Thrower, yet you create a new instance of EventThrower and call test() on that instance. You never subscribed to the event on that instance, so your handler doesn't run.

It should be:

_Thrower.ThrowEvent += (sender2, args) => { DoSomething(); }; _Thrower.test(); 


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