另一类.NET2简化委托WinForm的事件 [英] WinForm events in another class .NET2 Simplify delegate

查看:109
本文介绍了另一类.NET2简化委托WinForm的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Any way to make this working code simpler ie the delegate { }?

 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#中的事件

推荐答案

如果不认为你可以simplyfy:

If don't think you could simplyfy:

public event EventHandler ConnectionSuccessEvent = delegate { }

甚至在C#3 +你只能做

even in c#3 + you could only do

public event EventHandler ConnectionSuccessEvent = () => { }



不过,你可以简化

However you could simplify

codeDevice.ConnectionSuccessEvent += new EventHandler(SetupDeviceForConnectionSuccessState);



to

codeDevice.ConnectionSuccessEvent += SetupDeviceForConnectionSuccessState;

这篇关于另一类.NET2简化委托WinForm的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆