泛型+委托+Lambda表达式+拓展方法的简单应用
Lambda表达式:Lambda表达式是一种特殊的匿名方法,操作符是“=>” ,左面是参数列表,右侧为执行代码,如果执行代码只有一行语句,return关键字可以省略。
例子:(x, y) => x + y),参数列表:(x, y),执行代码:return x + y
(x, y) => x > y ? x : y),参数列表:(x, y),执行代码:return x > y ? x : y
demo:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueTest { class Program { static void Main(string[] args) { int[] a = new int[] { 1, 2, 3, 4 }; Console.WriteLine("数组和:{0}", a.Cumulate((x, y) => x + y));//第一种调用方式:拓展方法调用 Console.WriteLine("数组差:{0}", a.Cumulate((x, y) => x - y)); Console.WriteLine("数组积:{0}", a.Cumulate((x, y) => x * y)); Console.WriteLine("数组商:{0}", a.Cumulate((x, y) => x / y)); Console.WriteLine("最大值:{0}", a.Cumulate((x, y) => x > y ? x : y)); Console.WriteLine("最小值:{0}", a.Cumulate((x, y) => x < y ? x : y)); double[] d = new double[] { 1.11, 2.22, 3.33 }; Console.WriteLine("double数组和:{0}", Operation.Cumulate(d, (x, y) => x + y));//第二种调用方式:类的静态方法调用 float[] f = new float[] { 1.1f, 2.2f, 3.3f }; Console.WriteLine("float数组和:{0}", f.Cumulate((x, y) => x + y)); Console.ReadLine(); } } public static class Operation { //定义一个委托 public delegate T BiOperator<T>(T x, T y); //T[](数组)的拓展方法,泛型 public static T Cumulate<T>(this T[] array, BiOperator<T> op) { T s = array[0]; for (int i = 1; i < array.Length; i++) { s = op(s, array[i]); } return s; } } }


浙公网安备 33010602011771号