如何在 C# 中订阅其他类的事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/913374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:03:14  来源:igfitidea点击:

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

c#events.net-2.0event-handling

提问by sarsnake

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

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

How do I do that?

我怎么做?

Note that the form and custom class are separate classes.

请注意,表单和自定义类是单独的类。

采纳答案by CSharpAtl

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.....
    }
}

回答by Reed Copsey

Inside your form:

在您的表单中:

private void SubscribeToEvent(OtherClass theInstance) => theInstance.SomeEvent += this.MyEventHandler;

private void MyEventHandler(object sender, EventArgs args)
{
    // Do something on the event
}

You just subscribe to the event on the other class the same way you would to an event in your form. The three important things to remember:

您只需像订阅表单中的事件一样订阅另一个类上的事件。要记住的三个重要事项:

  1. You need to make sure your method (event handler) has the appropriate declaration to match up with the delegate type of the event on the other class.

  2. The event on the other class needs to be visible to you (ie: public or internal).

  3. Subscribe on a valid instance of the class, not the class itself.

  1. 您需要确保您的方法(事件处理程序)具有适当的声明以与其他类上的事件的委托类型相匹配。

  2. 另一个类上的事件需要对您可见(即:公共或内部)。

  3. 订阅类的有效实例,而不是类本身。

回答by Rex M

Assuming your event is handled by EventHandler, this code works:

假设您的事件由 EventHandler 处理,则此代码有效:

protected void Page_Load(object sender, EventArgs e)
{
    var myObj = new MyClass();
    myObj.MyEvent += new EventHandler(this.HandleCustomEvent);
}

private void HandleCustomEvent(object sender, EventArgs e)
{
    // handle the event
}

If your "custom event" requires some other signature to handle, you'll need to use that one instead.

如果您的“自定义事件”需要其他一些签名来处理,则您需要使用该签名。