应用场景
当我们在cs类中给其他窗体中的控件赋值或者设置属性时,因为在cs类中无法获取的其他窗体上的控件,所以通过订阅事件的方式,当事件触发,订阅事件的函数也会执行,此间进行参数传递
实例
新建Monitor类,添加自定义委托和事件,执行事件时参数和委托的参数相同
class Monitor
{
//定义委托
public delegate void DelegateTest(string s);
//定义事件
public static event DelegateTest EventTest;
public void onEventTest(string s)
{
if (EventTest != null)
{
EventTest(s);
}
}
}
在窗体控件添加文本框控件,并在窗体初始化中订阅事件
public Form1()
{
InitializeComponent();
Monitor monitor = new Monitor();
//先取消订阅
Monitor.EventTest -= new Monitor.DelegateTest(changeTextBox);
//将changeTextBox订阅事件
Monitor.EventTest += new Monitor.DelegateTest(changeTextBox);
}
public void changeTextBox(string s)
{
this.textBox1.Text = s;
}
}
在主程序中测试,模拟触发自定义事件,触发自定义事件后,会执行订阅此事件的所有函数
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form aa = new Form1();
string s = "hello";
Monitor monitor = new Monitor();
//判断事件是否为空
if(onEventTest != null)
{
monitor.onEventTest(s);
}
Application.Run(aa);
}
效果如下: