nametmp

导航

对C#委托的理解

我对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,会阻塞本线程
            }        
        }
    }
}

posted on 2008-07-10 12:01  nametmp  阅读(826)  评论(4编辑  收藏  举报