什么是委托 如何使用委托 声明,如: 1 namespace Vczx.ProCSharp.Exc
2 { 3 delegate double MathsOp( double x ); 4 //class defination here 5 } 这就声明了一个委托,意义:任何一个返回值为double,且只有一个形参为double的函数,都可以用这个委托来调用。 实例化: 首先我们要先有一个满足委托声明的方法,假设一个返回一个数的2倍的方法: 1class MathsOperations
2{ 3 public static double MultiplyBy2( double value ) 4 { 5 return value * 2; 6 } 7} 有了这样一个方法,我们就可以实例化一个委托了: 在实例化完一个委托之后,就可以用这个委托来调用方法了: 例子代码: 1namespace Vczx.ProCSharp.Exc
2{ 3 delegate double MathsOp( double x ); 4 class Start 5 { 6 public class MyDelegate 7 { 8 public static double MultiplyBy2( double x ) 9 { 10 return x * 2; 11 } 12 } 13 [STAThread] 14 static void Main(string[] args) 15 { 16 MathsOp operation = new MathsOp( MyDelegate.MultiplyBy2 ); 17 double x = 1.23; 18 double result = operation( x ); 19 Console.WriteLine( "{0} multiply by 2 is {1}", x, result ); 20 Console.Read(); 21 } 22 } 23} 多路广播委托 1namespace Vczx.ProCSharp.Exc
2{ 3 public class MyDelegate 4 { 5 public static void MultiplyBy2( double value ) 6 { 7 double result = value * 2; 8 Console.WriteLine( "Multiplying by 2: {0} gives {1}", value, result ); 9 } 10 11 public static void Squre( double value ) 12 { 13 double result = value * value; 14 Console.WriteLine( "Squaring: {0} gives {1}", value, result ); 15 } 16 } 17 18 delegate void MathsOp( double x ); 19 20 class Start 21 { 22 [STAThread] 23 static void Main(string[] args) 24 { 25 MathsOp operation = new MathsOp( MyDelegate.MultiplyBy2 ); 26 operation += new MathsOp( MyDelegate.Squre ); 27 double x = 1.23; 28 operation( x ); 29 30 operation -= new MathsOp( MyDelegate.MultiplyBy2 ); 31 operation( x ); 32 33 Console.Read(); 34 } 35 } 36} 输出: 注意,多路广播委托声明时必须返回void,否则返回值不知道应该送回什么地方。对此,我做了一个测试:如果不将委托的声明返回void,则返回值返回的是最后一个链入委托链的方法的返回值,编译不会出错。
|
|