一个简单的场景:一个引发事件的自定义类。我希望在表单中使用此事件并对其使用react。
我该怎么做?
请注意,表单和自定义类是单独的类。
最佳答案
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# - C#中如何订阅其他类(class)的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/913374/