WinForm事件在另一个类.net 2简化委托
本文关键字:net 事件 另一个 WinForm | 更新日期: 2023-09-27 18:16:31
有什么方法可以使这个工作代码更简单吗?
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);
codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;