Csharp/C#教程:另一个类.NET2中的WinForm事件简化了委托分享


另一个类.NET2中的WinForm事件简化了委托

任何使这个工作代码更简单的方法,即委托{}?

public partial class Form1 : Form { private CodeDevice codeDevice; public Form1() { InitializeComponent(); codeDevice = new CodeDevice(); //subscribe to CodeDevice.ConnectionSuccessEvent and call Form1.SetupDeviceForConnectionSuccessSate when it fires codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState); } private void SetupDeviceForConnectionSuccessState(object sender, EventArgs args) { MessageBox.Show("It worked"); } private void button1_Click(object sender, EventArgs e) { codeDevice.test(); } } public class CodeDevice { public event EventHandler ConnectionSuccessEvent = delegate { }; public void ConnectionSuccess() { ConnectionSuccessEvent(this, new EventArgs()); } public void test() { System.Threading.Thread.Sleep(1000); ConnectionSuccess(); } } 

WinForm事件订阅另一个类

如何在c#中订阅其他类的事件?

如果不认为你可以简单地说:

 public event EventHandler ConnectionSuccessEvent = delegate { } 

即使在c#3 +你也只能这样做

 public event EventHandler ConnectionSuccessEvent = () => { } 

但是你可以简化

 codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState); 

上述就是C#学习教程:另一个类.NET2中的WinForm事件简化了委托分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/936317.html

(0)
上一篇 2021年11月7日
下一篇 2021年11月7日

精彩推荐