委托应该是为了实现异步操作,委托一般分为5步:
1.定义一个委托;
2.根据委托定义实现方法;
3.创建委托变量;
4.委托变量与方法关联;
5.调用委托传递消息。
给一个实例让你直观的明白委托。
winForm 两个button,两个Label即可。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DelegateDemo1
{
//1.定义委托
public delegate int MyCalculator(int num);
public partial class Form1 : Form
{
//3.创建委托变量
private MyCalculator add;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.label2.Text = MyTask1(100).ToString();
this.label3.Text = MyTask2(100).ToString();
}
//2.根据委托定义实现方法
private int MyTask1(int num)
{
Thread.Sleep(1000);
return num * num;
}
private int MyTask2(int num)
{
return num * num;
}
private void buttonX1_Click(object sender, EventArgs e)
{
//4.委托变量与方法关联
add = MyTask1;
IAsyncResult result = add.BeginInvoke(10, null, null);
this.label2.Text = ("正在计算,请稍后......");
this.label3.Text = MyTask2(10).ToString();
//调用委托传值
int res = add.EndInvoke(result);
this.label2.Text = res.ToString();
}
}
}