using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp6 { class Program { public delegate void SaySomething(string name); //定义委托 public static event SaySomething peopleCome; //定义事件 关注SaySomething委托,当事件发生的时候,会通知关注的“委托”(再由这些“委托”去调用具体的方法)。 private delegate double DoCallFunc(double num1, double num2); static void Main(string[] args) { peopleCome += SayHello; //注册方法到事件上 peopleCome += SayNiceToMeetYou; //注册方法到事件上 peopleCome += SayGoodbye; //注册方法到事件上 peopleCome("张三"); //绑定触发事件 Console.WriteLine("====================================="); int x = 10; int y = 3; // DoCallFunc md = new DoCallFunc(Add); DoCallFunc df; df = Add; Console.WriteLine("callFunc:{0}", df(x, y)); df = Sub; Console.WriteLine("callFunc:{0}", df(x, y)); df = Multiply; Console.WriteLine("callFunc:{0}", df(x, y)); df = Divide; Console.WriteLine("callFunc:{0}", df(x, y)); Console.WriteLine("====================================="); Console.WriteLine("callFunc:{0}", Calculate(x, y, Add)); Console.WriteLine("callFunc:{0}", Calculate(x, y, Sub)); Console.WriteLine("callFunc:{0}", Calculate(x, y, Multiply)); Console.WriteLine("callFunc:{0}", Calculate(x, y, Divide)); Console.ReadKey(); } #region 普通委托 private static double Calculate2(double num1, double num2, DoCallFunc doCallFunc) { return doCallFunc(num1, num2); } #endregion #region 泛型委托 /* 泛型Action<T>委托表示引用一个void返回类型的方法。Action<T>委托类存在不同的变体,可以传递至多16种不同的参数类型, 没有泛型参数的Action类可以调用没有参数的方法。 例如:Action<in T1>调用带一个参数的方法,Action<in T1,in T2>调用带两个参数的方法等 Func<T>的用法和Action<T>用法类似,但是Func<T>表示引用一个带返回类型的方法, Func<T>也存在不同的变体,至多可以传递16个参数类型和1个返回类型, 例如:Func<in T1,out Resout>表示带一个参数的方法,Func<in T1,in T2,out Resout>表示调用带两个参数的方法。 */ private static double Calculate(double num1, double num2, Func<double, double, double> callFunc) { return callFunc(num1, num2); } #endregion #region 数字的加减乘除 private static double Add(double num1, double num2) { Console.WriteLine("{0} + {1} = {2}", num1, num2, num1 + num2); return num1 + num2; } private static double Sub(double num1, double num2) { Console.WriteLine("{0} - {1} = {2}", num1, num2, num1 - num2); return num1 - num2; } private static double Multiply(double num1, double num2) { Console.WriteLine("{0} * {1} = {2}", num1, num2, num1 * num2); return num1 * num2; } private static double Divide(double num1, double num2) { Console.WriteLine("{0} / {1} = {2}", num1, num2, num1 / num2); return Math.Round(num1 / num2, 2, MidpointRounding.AwayFromZero); //4舍5入 } #endregion #region 测试 public static void SayHello(string name) { Console.WriteLine("Hello," + name + "!"); } public static void SayNiceToMeetYou(string name) { Console.WriteLine("Nice to meet you," + name + "!"); } public static void SayGoodbye(string name) { Console.WriteLine("Bye bye," + name + "!"); } #endregion } }