C#,如何创建一个事件并在另一个类中侦听它?

编程入门 行业动态 更新时间:2024-10-08 19:49:22
本文介绍了C#,如何创建一个事件并在另一个类中侦听它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道如何执行此操作,这是示例代码.我想做的事.

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表达式以外的其他东西.请参阅 msdn.microsoft/en-us/library/17sde2xt.aspx 以获得更详尽的解释

Note: You could register your own delegates and work with something other than lambda expressions. See msdn.microsoft/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#,如何创建一个事件并在另一个类中侦听它?

本文发布于:2023-11-28 04:10:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   创建一个   类中   事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!