我對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,會阻塞本線程
}
}
}
}