C# Delegate
1: Declare the Delegate
delegate int DelegateName (int i, string s);
Define return name of Delegate delegate need to be handle
2: Use Delegate
DelegateName func = someFunction
就 像使用其他任何类型的name一样(int age = something),这里我们declar a 变量func(类型为DelegateName).接下来assign someFunction(这里的function需要与Delegate的返回值一样)。
int result = func(3, "hello"); //然后我们就可以call function就像call普通function一样。这里的int result接受func返回数值,func指向方法someFunction,这里有int 3,和string "hello"传入
int someFunction(int i, string s) //Next we need write someFunction callback, 注意格式需要与delegate一致,2个参数,返回值为int
{
...
}
实例代码:
Program.cs(Console Project)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace UsingDelegate 7 { 8 public delegate int NumberFunction(int x); //Declare the delegate, Name:NumberFunction, have one int and return int 9 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 NumberFunction f = Square; //因为我们上面Declare了Delegate,这里我们就可以作为一个变量用。变量f类型NumberFunction,付给了一个同样格式 的函数Square。想象下f是指针指向一个methord,现在指向的是Square方法。 15 Console.WriteLine("resulte of the delegate is {0}", f(5)); 16 17 //now change the delegate point 18 f = Cube; //注意这里赋值要同类型,不要写成Cube(),Call()是类型,而f是delegate类型 19 Console.WriteLine("resulte of the delegate is {0}", f(5)); 20 21 Console.ReadLine(); 22 } 23 24 static int Square(int num) // Follow the delegate description, take one int and return int 25 { 26 return num * num; 27 } 28 static int Cube(int num) // Follow the delegate description, take one int and return int 29 { 30 return num * num * num; 31 } 32 33 } 34 }