自学的时候看到很多关于委托方法的文章,但是始终不明白,代码可以写的简单一些,为什么有的却要写的很复杂!想咨询一下,复杂写的优点是什么?
网上的代码示例
public partial class Form2 : Form
{
Thread myThread;
private delegate void MyDelegateUI();//定义委托
private MyDelegateUI myDelegate;//声明委托
public Form2()
{
InitializeComponent();
myThread = new Thread(doWork);
myDelegate=new MyDelegateUI(refreshRichListBox);
}
private void refreshRichListBox()
{
richTextBox1.AppendText( "Hello Delegate \r");
}
private void doWork()
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
this.richTextBox1.Invoke(myDelegate);
Application.DoEvents();
}
}
private void button1_Click(object sender, EventArgs e)
{
myThread.Start();
}
}
}
以下是我认为简单的写法,比较清晰,
public partial class Form2 : Form
{
Thread myThread;
private delegate void MyDelegateUI(); //定义委托
public Form2()
{
InitializeComponent();
}
private void refreshRichListBox()
{
richTextBox1.AppendText( "Hello Delegate \r");
}
private void doWork()
{
for (int i = 0; i < 10; i++)
{
this.richTextBox1.Invoke(new MyDelegateUI(refreshRichListBox));
Thread.Sleep(1000);
Application.DoEvents();
}
}
private void button1_Click(object sender, EventArgs e)
{
myThread = new Thread(doWork);
myThread.Start();
}
}
}