WinForm事件订阅到另一个类

本文关键字:另一个 事件 WinForm | 更新日期: 2023-09-27 18:16:12

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

我试图让我的winform UI订阅eventthrow类中的事件。DoSomething never fire .

如何订阅其他课程'c#中的事件?

WinForm事件订阅到另一个类

事件不是静态的,对于的每个EventThrower实例,存在一个EventHandler实例。

您订阅了_Thrower上的事件,但是您创建了EventThrower的新实例并在上调用该实例上的test()。您从未订阅过该实例上的事件,因此您的处理程序不会运行。

应该是:

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

这是因为您在调用test之前创建了一个新的EventThrower。

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

:

    _Thrower.test();

它会调用DoSomething