using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace ConsoleDelegateAnonymous { class Test { public int Add(int x, int y) { return x + y; } } internal class Program { //定义委托 public delegate int DAdd(int x, int y); static void Main(string[] args) { Test test = new Test(); //将委托与Add方法相关联 DAdd d = test.Add; //再想调用Test类中的Add方法时,直接调用委托就可以了 int num = d(2, 3); Console.WriteLine("num:" + num); //定义匿名方法(大括号外需要加分号) DAdd d1 = delegate(int x,int y) { //由于定义委托时有返回值类型,因此在定义匿名方法时 //也一定要有返回值为相同类型的语句 return x + y; }; //调用 int num2 = d1.Invoke(5, 6); Console.WriteLine("num2:" + num2); Console.ReadLine(); } } }