sar*_*ake 18 c# events event-handling .net-2.0
一个简单的场景:一个引发事件的自定义类.我希望在表单中使用此事件并对其做出反应.我怎么做?代码示例,请!
请注意,表单和自定义类是单独的类.
CSh*_*Atl 27
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.....
}
}
Run Code Online (Sandbox Code Playgroud)
在你的表格内:
private void SubscribeToEvent(OtherClass theInstance) => theInstance.SomeEvent += this.MyEventHandler;
private void MyEventHandler(object sender, EventArgs args)
{
// Do something on the event
}
Run Code Online (Sandbox Code Playgroud)
您只需按照与表单中的事件相同的方式订阅其他类上的事件.要记住的三件重要事情:
1)您需要确保您的方法(事件处理程序)具有适当的声明以匹配另一个类上的事件的委托类型.
2)您需要看到其他课程的事件(即:公共或内部).
3)订阅类的有效实例,而不是类本身.