iT邦幫忙

0

C# delegate 委派

好開心啊~
抄人家的程式,抄了這麼久,終於懂了委派了.

做了3個委派
一個只有方法
一個是方法(變數)
一個是方法(變數,變數)
一開始我們要先宣告委派,再來實作委派.
要用的時侯用beginkIvoke,再裡面new 委派(再把實作的function放進去)
https://ithelp.ithome.com.tw/upload/images/20180104/20106764BJlzri0ZBz.png

        delegate void d1();//宣告委派
        private void _d1()//實作委派
        {
            textBox1.Text = "d1";
        }
        private void button6_Click(object sender, EventArgs e)
        {
            this.  BeginInvoke(                //呼叫
                            new d1(            //new 委派
                                      _d1      //把實作function放進來
                                   )
                             );
        }

        delegate void d2(string val);
        private void _d2(string val)
        {
            textBox1.Text  +=Environment.NewLine+ val ;
        }
        private void button7_Click(object sender, EventArgs e)
        {
            this.BeginInvoke(
                            new d2(_d2)          //new委派,把實作function放進來
                            ,new object []{"d2"} //變數,new object[],把變數放進來
                            );
        }
        delegate void d3(Control ctr, string val);
        private void _d3(Control ctr, string val)
        {
            if (Ctrl is TextBox)
            {
              TextBox tx = (TextBox)ctr;
              tx.Text += Environment.NewLine+"d3:"+val;
            }
        }
        private void button8_Click(object sender, EventArgs e)
        {
            this.BeginInvoke(new d3(_d3),new object[]{textBox1,DateTime.Now.ToString()});
        }

用到的地方
1.不同執行緒間的變數存取.e.g.執行緒A,想set執行緒B的lable.text


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0

變數,參數,傻傻分不清楚。

我要留言

立即登入留言