如何在c#中订阅其他类的事件? [英] How to subscribe to other class' events in c#?
本文介绍了如何在c#中订阅其他类的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个简单的场景:引发事件的自定义类。我希望在一个表单内消费这个事件并作出反应。我怎么做?
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? Code examples, please!
请注意,表单和自定义类是单独的类。
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屋!
查看全文