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

时间:2011-12-01 00:37:02

标签: c# winforms events

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

 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 event subscription to another class

How to subscribe to other class' events in c#?

1 个答案:

答案 0 :(得分:0)

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

public event EventHandler ConnectionSuccessEvent = delegate { }

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

public event EventHandler ConnectionSuccessEvent = () => { }

但是你可以简化

codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);

codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;