using System; namespace DelegateDemo { class Program { /// /// 泛型委托 /// /// /// /// /// /// public delegate int ProcessDelegate(T a, S b, V v); /// /// 委托 /// /// /// /// public delegate int ProcessDelegate(int a, int b); static void Main(string[] args) { //静态调用 ProcessDelegate process = new ProcessDelegate(Add); ProcessDelegate processDelegate = new ProcessDelegate(Add); var a = processDelegate(5, 5, 5); Console.WriteLine(process(2, 4)); Console.WriteLine(Calculate(4, 3, Add )); Console.WriteLine(Calculate(4, 3,5, Add)); Console.WriteLine(a); //实例调用 Test test = new Test(); ProcessDelegate processA = new ProcessDelegate(test.Add); Console.WriteLine(processA(5, 8)); ProcessDelegate processB = (ProcessDelegate)Delegate.Combine(process , processA); //调用了Delegate.Combine()方法,通过名称可以指定它用于将多个委托组合起来,调用test3时,会按照它的参数顺序执行所有方法。这种方式有时候非常有用,因为我们很可能在某个事件发生时,要执行多个操作。 Console.WriteLine(Calculate(50, 10, processB)); //Func调用从无参到16个参数共有17个重载,用于分装有输入值而且有返回值的方法。如:delegate TResule Func(T obj); Func func = new Func(Add); //Action 从无参到16个参数共有17个重载,用于分装有输入值而没有返回值的方法。如:delegate void Action(T obj); Action action = new Action(test.Say); Console.WriteLine(func(5, 9)); } //执行委托 public static int Calculate(int a, int b, ProcessDelegate process) { return process(a, b); } public static int Calculate(int a, int b, int c , ProcessDelegate process) { return process(a, b , c); } public static int Add(int a, int b) { return a + b; } public static int DS(int a, int b) { return a + b; } public static int Add(int a, int b, int c) { return a + b + c; } } public class Test { public int Add(int a, int b) { return a + b; } public void Say(int a, int b) { Console.WriteLine(a + b); } } }