用Action实现事件(有参数,无返回值)

    //1、声明委托
    //忽略
    //2、声明委托事件
    //ublic static Action<int> act1;//Action封装一个方法,该方法具有1个参数并且不返回值。
    //public static Action<int, string> act2;//Action封装一个方法,该方法具有2个参数并且不返回值。
    //public static Action<int, string, int> act3;//Action封装一个方法,该方法具有3个参数并且不返回值。

    public static Action<bool> act1;//Action封装一个方法,该方法具有1个参数并且不返回值。
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //3、订阅事件
        act1+= PlcConnect;
    }
    //4、触发事件
    private void button1_Click(object sender, EventArgs e)//执行Click方法,触发事件
    {
        if (act1!= null) //是否被订阅
            act1(true); //发布事件
    }
    private void button2_Click(object sender, EventArgs e)
    {
        if(act1!= null) //是否被订阅
            act1(false); //发布事件

    }
    //5、执行的方法
    private void PlcConnect(bool make)
    {
        if (make == true)
            label1.Text = "打开连接";
        else
            label1.Text = "断开连接";
    }

posted on 2025-10-02 13:31  lyc6921  阅读(12)  评论(0)    收藏  举报

导航