C#,如何创建一个事件并在另一个类中侦听它? [英] C#, How to create an event and listen for it in another class?
问题描述
我不知道如何执行此操作,这是示例代码.我想做的事.
I can't figure out how to do this, heres sample code. Of what I wish to do.
public Class MainForm : Form
{
MyUserControl MyControl = new MyUserControl;
private void Button_Click(object sender, EventArgs e)
{
//Create MyEvent
}
}
public Class MyUserControl : UserControl
{
//listen for MyEvent from MainForm, and perform MyMethod
public void MyMethod()
{
//Do Stuff here
}
}
推荐答案
第1步)在MainForm上公开一个事件……说.
Step 1) Expose an event on MainForm... say..
public event Action simpleEvent
第2步)给MyUserControl一个构造函数,该构造函数采用MainForm的一个实例并将一个操作绑定到该事件
Step 2) Give MyUserControl a constructor that takes an instance of MainForm and bind an action to that event
public MyUserControl(MainForm form) {
form += () => Console.WriteLine("We're doing something!")
}
第3步)在MainForm.Button_Click中引发事件
Step 3) raise the event in MainForm.Button_Click
if(simpleEvent != null) simpleEvent();
注意:您可以注册自己的委托并使用lambda表达式以外的其他东西.请参阅 http://msdn.microsoft.com/en-us/library/17sde2xt.aspx 以获得更详尽的解释
Note: You could register your own delegates and work with something other than lambda expressions. See http://msdn.microsoft.com/en-us/library/17sde2xt.aspx for a more thorough explanation
您的最终结果将看起来像...
Your end result would look like...
public Class MainForm : Form
{
public event Action MyEvent;
MyUserControl MyControl = new MyUserControl(this);
private void Button_Click(object sender, EventArgs e)
{
if(simpleEvent != null) simpleEvent();
}
}
public Class MyUserControl : UserControl
{
//listen for MyEvent from MainForm, and perform MyMethod
public MyUserControl(MainForm form) {
simpleEvent += () => MyMethod();
}
public void MyMethod()
{
//Do Stuff here
}
}
这篇关于C#,如何创建一个事件并在另一个类中侦听它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!