對C#委託的理解

來源:互聯網
上載者:User
我對C#委託的理解一直是模糊的,今天好像有點感覺,特把它記錄下來。如果說的不對,請各位不吝賜教。
委託——形似“函數”的“類級”“函數指標”,三個關鍵:1、形式上像函數,2、屬於類一級,3、本質是函數指標,是一座調用其他函數橋樑。以下是代碼解析:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;

namespace WebBrowser
{
    //1、聲明:形式像函數,只是多了關鍵字delegate;因為是類級,所以其位置與其他類並列
    delegate void dUpdateStatus(string url);  

    public partial class FormMain : Form
    {       
        Thread tRecord;
       
        public FormMain()
        {
            InitializeComponent();

            tRecord = new Thread(new ParameterizedThreadStart(Record));
        }

        private void btRecord_Click(object sender, EventArgs e)
        {
            tRecord.Start();
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            tRecord.Abort();
        }

        private void Record(object url)
        {
         
            url = "http://www.sina.com.cn/**.shtml";
          
            //2、指向被委託的方法: 可以用匿名方法填充 或 指向命名的方法
            dUpdateStatus du = new dUpdateStatus
                (
                    //這裡用匿名方法來填充委託,其輸入的參數要與委託的參數一致
                    delegate(string urlcatch)
                    {
                        tbStatus.Text += urlcatch + "\r\n";
                    }
                );

            //3、使用:直接調用 或 被調用
            //du(entry.URL);                 //直接調用。因本線程不是ui線程,會提示錯誤
            this.BeginInvoke(du, url); //被begininvoke調用,非同步更新ui
            //this.Invoke(du, entry.URL);    //被invoke     調用,同步更新ui,會阻塞本線程
            }        
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.