C#使用异步委托在另一个线程上更新窗体不能省略可选参数

使用button1更新label1:

        private delegate void UpdateFormInvoke(string a, string b = "B");
        private void UpdateForm(string a, string b = "B")
        {
            label1.Text = a + " - " + b;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(Test);
            th.Start();
        }

        void Test()
        {
            UpdateFormInvoke uli = new UpdateFormInvoke(UpdateForm);
            this.BeginInvoke(uli, new object[] { "A" });
        }

 

参数计数不匹配异常:

 

 

修改代码1:

        private delegate void UpdateFormInvoke(string a, string b = "B");
        private void UpdateForm(string a, string b)
        {
            label1.Text = a + " - " + b;
        }

 

修改代码2:

        private delegate void UpdateFormInvoke(string a, string b);
        private void UpdateForm(string a, string b = "B")
        {
            label1.Text = a + " - " + b;
        }

 

结果出现相同的错误

 

修改代码3:

        void Test()
        {
            UpdateFormInvoke uli = new UpdateFormInvoke(UpdateForm);
            this.BeginInvoke(uli, new object[] { "A", "B" });
        }

 

不省略可选参数,无异常。

 

posted @ 2018-03-03 12:35  X2009  阅读(266)  评论(0编辑  收藏  举报