四种委托使用方法

  
   public delegate int MethodDelegate(int x,int y);//delegate 定义一个委托
//实例化一个委托对象 MethodDelegate methodDelegate = new MethodDelegate(Add); Console.WriteLine(methodDelegate(1, 2)); // Action 类型的委托,跟返回值为void,传入参数为string类型的方法匹配 Action<string> action = new Action<string>(SayHello); action("cherry"); //Func 类型的委托,跟返回值为void,传入参数为string类型的方法匹配 Func<int, int, string> func = new Func<int, int, string>(ConcatInt); Console.WriteLine(func(1, 2)); //Predicate 类型的委托,返回一个bool值 Predicate<string> predicate = new Predicate<string>(string.IsNullOrEmpty); Console.WriteLine(predicate("123")); public static string ConcatInt(int x,int y) { return x + y + ""; } public static void SayHello(string name) { Console.WriteLine(name); } public static int Add(int x,int y) { return x + y; }

1.用 delegate 定义一个委托 public delegate  方法返回值 委托名(方法参数名)

2. Action<T> 是一个无返回值的泛型委托, T为方法的传入参数的类型

3.Func<T1, T2, T3> 是一个有返回值的泛型委托,最后一个参数类型是方法的返回值类型,其他的为方法的传入参数的类型

4.Predicate<T1> 是一个返回bool类型的泛型委托 

原文地址:https://www.cnblogs.com/xiaoxinstart/p/13819173.html