1. 程式人生 > >C#使用異步委托在另一個線程上更新窗體不能省略可選參數

C#使用異步委托在另一個線程上更新窗體不能省略可選參數

leg pos orm blog tar log 委托 () gin

使用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" });
        }

不省略可選參數,無異常。

C#使用異步委托在另一個線程上更新窗體不能省略可選參數