关于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+"" );
}
委托的使用要先定义,然后声明,然后实例化,然后作为参书进行传递,最后才能使用。