C#中的委托到底是什么概念??
委托,简单理解是这样的.
比如您要管您的孩子,把孩子送进了幼儿园.
OK.此时您就把您的孩子委托给了幼儿园.
当幼儿园放学,将孩子交还给您的手中.则是委托的回调.
当然我这里的例子是说异步委托调用.您也可以同步.
什么是同步委托调用?
您去银行存钱.把钱给柜员.他们帮你点钞.存款然后给您存折或卡.
那么您就相当于把钱委托给了柜员让他去执行存钱的这个函数.
(这个概念转自百度)
Delegate委托是自定义的委托,定义和使用如下代码
无返回值的定义和使用
class Program
{
private delegate void WT();
//定义一个委托,返回值为空,委托名为WT
static void Test()
//定义一个空返回值的Test方法
{
Console.WriteLine("这就是委托");
}
static void Main(string[] args)
{
WT wt = Test;
//这里是赋值Test方法的引用,所以不带()
wt();
Console.ReadKey();
}
}
}
在上面的代码里,我们可以看到委托的对象wt可以直接用Test方法的引用去实例,所以wt()=Test(),两者的输出结果都为“这就是委托”
接下来我们看有返回值的定义和使用
class Program
{
public delegate int Test(int num, int num1);
//定义一个int类型的委托,带有两int类型个参数,委托名为Test
static int Chenfa(int num,int num1)
//定义一个int类型的方法,带有两个int类型参数,返回两个数的积
{
return num * num1;
}
static int Chufa(int num,int num1)
//定义一个int类型的方法,带有两个int类型参数,返回两个数的商
{
return num / num1;
}
static void Main(string[] args)
{
Test te;//创建一个委托的对象te
te = Chenfa;//赋值Chenfa方法的引用
Console.WriteLine(te(20, 3));
//te(20,3)的结果为60
te = Chufa;//赋值Chufa方法的引用
Console.WriteLine(te(20, 5));
//te(20,5)的结果为4
Console.ReadKey();
}
}
在上面的代码里,如果自定义的方法是有返回值的方法,那么自定义的委托就必须有返回值,而且类型必须相同,如果方法里带有参数,那么委托也必须带有参数,同样的创建委托的对象te后用两个自定义的方法的引用去实例,那么te就可以去调用方法里的功能了
再来两个例子
案例1
class Program
{
private delegate string GetAstring();//定义了一个委托类型
static void Main(string[] args)
{
int x = 40;
string s = x.ToString();//把数据转换成字符串
//// Console.WriteLine(s);
GetAstring a=new GetAstring(x.ToString);//a指向了tostring方法
string s = a();//通过委托实例去调用x中的tostirng方法
GetAstring a = x.ToString;
string s = a.Invoke();//通过invoke方法调用a所引用的方法
Console.WriteLine(s);//通过委托调用一个方法,跟直接调用该方法是一样的
}
在上面的代码可以看到,GetAstring a=new GetAstring(x.ToString);和GetAstring a = x.ToString;虽然是两种写法虽然不同,但作用其实是一样的
案例2
使用委托类型作为方法的参数
class Program
{
private delegate void PrintString();
//定义一个空返回值的委托
static void Printstr(PrintString print)
//定义一个空返回值方法,参数为委托
{
print();//调用委托里的内容
}
//定义两个用于测试的方法Method1和Method2
static void Method1()
{
Console.WriteLine("method1");
}
static void Method2()
{
Console.WriteLine("method2");
}
static void Main(string[] args)
{
PrintString method =Method1;//用method1的引用实例委托对象method
Printstr(method);//调用Printstr方法,委托的对象method作为参数
method = Method2;//用Method2的引用实例委托对象method
Printstr(method);//调用Printstr方法,委托的对象method作为参数
Console.ReadKey();
}
}
当委托method使用Method1实例时,调用Priintstr(method)的结果为method1
当委托method使用Method2实例时,调用Priintstr(method)的结果为method2
所以委托可以作为方法的参数来使用,可以间接的从一个方法里调用另一个方法
本次的delegate委托就说到这。
至于不懂什么是对象,什么是引用,什么是对象实例化,什么是方法的这些得靠自己去了解
本篇博客是博主的学习笔记,希望对来看的人有所帮助,在解释方面觉得还是比较粗糙,请谅解,多多指教