转载:C# 委托知识总结
2010-07-29 11:00
232 查看
1.什么是委托,为什么要使用委托 我正在埋头苦写程序,突然想喝水,但是又不想自己去掉杯水而打断自己的思路,于是我就想让女朋友去给我倒水。她去给我倒水,首先我得让她知道我想让她干什么,通知她之后我可以继续写自己的程序,而倒水的工作就交给了她。这样的过程就相当于一个委托。 在程序过程中,当程序正在处理某个事件的时候,我需要另外的程序代码去辅助处理一些事情,于是委托另一个程序模块去处理,而委托就可以达到这种目的,我可以利用委托通知另外的程序模块,该去调用哪个函数方法。委托其实就起到了这样一个作用,将函数签名传递到了另一个函数中。或许这样讲还是有些模糊,看看后面的具体实例。 2.委托的定义 delegate int Add(int num1,int num2); delegate void ConvertNum(string result); 上面是定义两个委托的例子,其实很简单。声明一个委托使用delegate关键字,上面分别是定义的带返回值的委托和不带返回值的委托, 两个委托都有传递参数,当然也可以不传递参数。其实委托也是一个类,委托派生为System.MulticastDelegate,而System.MulticastDelegate 又继承System.Delegate,如果你知道这个也就明白委托其实是一个特殊的类。
原文:/content/3681555.html
异步委托回调函数 1 public delegate string AsyDelegate(string content); 2 3 public class AsyncresultDelegate 4 { 5 public void TestAsync() 6 { 7 AsyDelegate del = GetTea; 8 del.BeginInvoke("hechen", delegate(IAsyncResult ar) { 9 Thread.Sleep(5000); 10 string result = del.EndInvoke(ar); 11 Console.WriteLine(result); 12 }, null); 13 for (int i = 0; i < 100; i++) 14 { 15 Console.WriteLine("等待....."); 16 Thread.Sleep(1000); 17 } 18 } 19 20 public static string GetTea(string content) 21 { 22 return "茶来了 " + content; 23 } 24 }
原文:/content/3681555.html