另一个类.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); 

 codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;