如何在 C# 中订阅其他类的事件? [英] How to subscribe to other class' events in C#?

查看:32
本文介绍了如何在 C# 中订阅其他类的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的场景:一个引发事件的自定义类.我希望在表单中使用此事件并对其做出反应.

A simple scenario: a custom class that raises an event. I wish to consume this event inside a form and react to it.

我该怎么做?

注意表单和自定义类是独立的类.

Note that the form and custom class are separate classes.

推荐答案

public class EventThrower
{
    public delegate void EventHandler(object sender, EventArgs args) ;
    public event EventHandler ThrowEvent = delegate{};

    public void SomethingHappened() => ThrowEvent(this, new EventArgs());
}

public class EventSubscriber
{
    private EventThrower _Thrower;

    public EventSubscriber()
    {
        _Thrower = new EventThrower();
        // using lambda expression..could use method like other answers on here

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

    private void DoSomething()
    {
       // Handle event.....
    }
}

这篇关于如何在 C# 中订阅其他类的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆