标题:关于C#委托的经典实例
取消只看楼主
RayminCheung
Rank: 1
来 自:大连
等 级:新手上路
帖 子:1
专家分:0
注 册:2012-3-9
 问题点数:0 回复次数:0 
关于C#委托的经典实例
委托在C#编程中所占的地位是毋庸置疑的,委托概念也是区别于C/C++的重要方面,下面让我们以一个经典实例对委托做一个了解。

        private delegate void WriteTextBox(char ch);//定义委托
        private WriteTextBox writeTextBox;//声明

        private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                groupBox2.Text = "运行中...";
                groupBox2.Refresh();
                richTextBox1.Clear();
                richTextBox1.Refresh();
                writeTextBox = new WriteTextBox(WriTextBox1);//实例化委托
                WriTxt(writeTextBox);//作为参数
                groupBox2.Text = "任务1";
                textBox1.Focus();
                textBox1.SelectAll();
 
            }
            else richTextBox1.Clear();
            if (checkBox2.Checked == true)
            {
                //groupBox2.Refresh();
                groupBox3.Text = "运行中...";
                groupBox3.Refresh();
                richTextBox2.Clear();
                richTextBox2.Refresh();
                writeTextBox = new WriteTextBox(WriTextBox2);//实例化委托
                WriTxt(writeTextBox);//作为参书
                groupBox3.Text = "任务2";
                textBox1.Focus();
                textBox1.SelectAll();

            }
            else richTextBox2.Clear();
            
        }
        private void WriTxt(WriteTextBox wMethod)
        {
            string sta = textBox1.Text;
            for (int i = 0; i < sta.Length; i++)
            {
                wMethod(sta[i]);//使用委托
                DateTime now = DateTime.Now;
                while (now.AddSeconds(0.1) > DateTime.Now) { }
            }
        }
        private void WriTextBox1(char ch)
        {
            richTextBox1.AppendText(ch +"");
        }
        private void WriTextBox2(char ch)
        {
            richTextBox2.AppendText(ch+"" );
        }
 
   
    委托的使用要先定义,然后声明,然后实例化,然后作为参书进行传递,最后才能使用。
搜索更多相关主题的帖子: 经典 void private 
2012-03-10 20:10



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-362765-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.056491 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved