C#中的委托 Delegate
C# 中的委托就是用一个方法去调用另一个方法。在使用委托前必须先定义委托。委托的签名必须与方法签名保持一致。此外还有
必须有一个方法来实现委托与方法的调用(即用一个方法调用委托的方法)
1、委托 public delegate int DeleMathOperation(int value); //返回int ,参数 int 2、方法 public static int DoubleToTwo(int value) //返回iint ,参数int ,与委托保持一致 { return value * 2; } 3、调用委托方法(用一个方法来调用另一个方法,方法的参数为委托) public static void ProcessAndDisplayValue(DeleMathOperation action, int value) { int result = action(value); Console.WriteLine("The value is {0} ,and Result is {1}", value, result); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Wrox.ProeCSharp.JupiteBank; using Wrox.ProeCSharp.VenusBank; namespace Wrox.ProeCSharp { class MathOpration { public static int DoubleToTwo(int value) { return value * 2; } public static int Squre(int value) { return value * value; } } class Program { public delegate int DeleMathOperation(int value); static void Main(string[] args) { DeleMathOperation[] DeleteOp = {MathOpration.DoubleToTwo,MathOpration.Squre }; for (int i = 0; i < DeleteOp.Length; i++) { Console.WriteLine("Using the DeleteOp[{0}]:", i); ProcessAndDisplayValue(DeleteOp[i], 2); ProcessAndDisplayValue(DeleteOp[i], 5); ProcessAndDisplayValue(DeleteOp[i], 10); Console.ReadLine(); } } public static void ProcessAndDisplayValue(DeleMathOperation action, int value) { int result = action(value); Console.WriteLine("The value is {0} ,and Result is {1}", value, result); } } }