C#使用委託的簡單步驟

來源:互聯網
上載者:User

標籤:delegate   線程   

委託可以理解為C或C++裡面的函數指標,調用委託其實是調用被委託的方法。

簡單的使用委託的步驟如下:

1.定義委託

        // 定義委託使用關鍵字 delegate
        private delegate void SetProgressBarValueDelegate(int value);

2.聲明委託

       private SetProgressBarValueDelegate setProgressBarValue;

3.執行個體化委託

       setProgressBarValue = new SetProgressBarValueDelegate(SetProgressBarValue1);

    SetProgressBarValue1是被委託的方法名稱,參數類型要和委託的類型保持一致。其原型如下:

          // 設定進度條1值
        private void SetProgressBarValue1(int value)
        {
            pgProgressBar1.Value = value;
        }

4.使用委託:

    SetProgressBarValueMethod(setProgressBarValue);

        // 設定進度條值
        private void SetProgressBarValueMethod(SetProgressBarValueDelegate setProgressBarValueDelegate)
        {
            for (int i = 1; i <= 100; i++)
            {
                Application.DoEvents();
                Thread.Sleep(50);
                setProgressBarValueDelegate(i);  
            }
        }



/* 此命令可告訴系統繼續處理使用者介面的其它事件,避免假死
 * 等同於 Visual Basic 6.0 的 DoEvents()
 * 等同於 易語言 的 處理事件() */
 Application.DoEvents();
/* 此命令用於線程暫停(參數:毫秒)
 * 此處用在主線程中,會導致假死,加暫停只為了看得更清楚 */

Thread.Sleep(50);



C#使用委託的簡單步驟

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.