C#中已经为我们定义了一些委托类型,我们就不需要自己定义了
Func的委托
TResult表示返回的类型
Tx argx表示输入的参数
Func的委托可以没有输入的参数但是必须要有返回的类型
(1) *delegate TResult Func<TResult>();
(2)*delegate TResult Func<T1,TResult>(T1 arg1);
(3) *delegate TResult Func<T1,T2,TResult>(T1 arg1, T2 arg2);
(4)*delegate TResult Func<T1,T2,T3,TResult>(T1 arg1, T2 arg2, T3 arg3);
(5)*delegate TResult Func<T1,T2,T3,T4,TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
Action委托
Tx argx表示输入的参数
Action委托可以没有输入参数但是《一定没有》返回值
(1) * delegate void Action(); //无参,无返回值
(2)* delegate void Action<T>(T1 arg1);
(3)* delegate void Action<T1,T2>(T1 arg1, T2 arg2);
(4)* delegate void Action<T1,T2,T3>T1 arg1, T2 arg2, T3 arg3);
(5)* delegate void Action<T1,T2,T3,T4>T1 arg1, T2 arg2, T3 arg3, T4 arg4);
下面这段代码主要实现委托与界面的交互
#region 利用Action实现线程和界面交互
private void Updata(object str)
{
for (int i = 0; i <= 100; i++ )
{
Thread.Sleep(1 * 1000);
this.Invoke((Action)(() =>
{
progressBar.Value = i;
richTextBox.AppendText(i.ToString() + "\n");
}));
}
}
private void btn_Start_Click(object sender, EventArgs e)
{
WaitCallback wcb = new WaitCallback(Updata);
ThreadPool.QueueUserWorkItem(wcb,"Action");
}
#endregion