《委托二》
继上篇《委托一》http://www.cnblogs.com/fjsnail/archive/2013/06/14/3134871.html之后,今天继续学习委托。貌似很久没有二了,下来开始。
正如上篇介绍,委托就像是一个类,实际上他的申明就像是一个类
delete void Feedback(int value);
下面介绍一个比较全面的例子,例子比较好理解,在第一篇中有讲他的详细定义
这是简化的委托调用过程
Feedback fb3 = new Feedback(print); //最简单的调用委托方式:声明委托----指明回调函数-----执行委托回调函数 fb3.Invoke(15);//可以没有invoke()
delegate void Feedback(Int32 value); //1 声明一个委托 class Program { static void Main(string[] args) { StaticDelegateDemo(); InstanceDelegateDemo(); ChainDeleteDemo1(); ChainDeleteDemo2(); Console.ReadKey(); } private static void StaticDelegateDemo() { Console.WriteLine("------------StaticDeleteDemo--------------"); Counter(1, 5, null); //不传委托变量 Counter(1,5,new Feedback(print)); //有点像匿名对象 2.传递委托实例,并定义回调函数(其实是将引用传递给另个函数创建的实例) Counter(1,5,new Feedback(Program.print)); //加program Feedback fb = new Feedback(Program.print); //直接声明一个委托对象,赋予委托回调函数,并执行 fb(5); } private static void InstanceDelegateDemo() { Console.WriteLine("------------Instance Delegate Demo--------------"); Feedback fb1 = new Feedback(print); Feedback fb2 = new Feedback(Program.print); Counter(11,15,null); Counter(11,15,fb1); Counter(11, 15, fb2); Feedback fb3 = new Feedback(print); fb3(15); } private static void ChainDeleteDemo1() { Console.WriteLine("------------ChainDeleteDemo-------------------"); Feedback fb1 = new Feedback(print); Feedback fb2 = new Feedback(Program.print); //通过方法,增减委托 Feedback fb3 = new Feedback(Program.print); fb1=(Feedback)Feedback.Combine(fb1, fb2); fb1 = Feedback.Remove(fb1,fb2) as Feedback; Counter(21,25,fb1); } private static void ChainDeleteDemo2() { Console.WriteLine("------------ChainDeleteDemo2-------------------"); Feedback fb1 = new Feedback(print); Feedback fb2 = new Feedback(Program.print); //通过+-符号,增减委托 Feedback fb3 = new Feedback(Program.print); fb1 += fb2; fb1-=fb2; Counter(21, 25, fb1); } private static void print(Int32 value) { Console.WriteLine(value); } private static void Counter(Int32 from ,Int32 to,Feedback fb) { Int32 index; for(index=from;index<to;index++) { } if(fb!=null) //给回调函数赋值 fb(index); } }