C#学习笔记之泛型委托

来源:互联网 发布:什么是百度seo 编辑:程序博客网 时间:2024/06/03 15:51

求数组的最大值:

普通委托写法如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 求数组的最大值{    // 声明一个普通委托    public delegate int DelCompare(object o1, object o2);    class Program    {        static void Main(string[] args)        {            // 声明一个数组            object[] obj = { 2, 3, 4, 5, 6 };            // 匿名函数方法            //object result = GetMax(obj, delegate(object obj1, object obj2)            //{            //    int n1 = (int)obj1;            //    int n2 = (int)obj2;            //    return n1 - n2;            //});            // lamda表达式方法。            object result = GetMax(obj, (object obj1, object obj2) =>            {                int n1 = (int)obj1;                int n2 = (int)obj2;                return n1 - n2;            });            Console.WriteLine(result);            Console.ReadKey();        }        // 方法中传入一个数组和一个指向方法的委托。        public static object GetMax(object[] nums, DelCompare del)        {            object max = nums[0];            for (int i = 0; i < nums.Length; i++)            {                if (del(max, nums[i]) < 0) // 通过委托判断最大值                {                     max = nums[i];                }            }            return max;        }    }}

泛型委托写法如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    // 声明普通的委托    //public delegate int Compare(object obj1, object obj2);    // 声明一个泛型委托:声明中所有的类型全部写成(T),委托名和方法名后要加(<T>)。    public delegate int Compare<T>(T obj1, T obj2);    class Program    {        static void Main(string[] args)        {            int[] obj = { 1, 2, 3, 4, 5, 6 };            // 调用时,方法名后写什么类型,后面所有的类型都会自动转成什么类型。            // 匿名函数写法            //int n = GetMax<int>(obj, delegate(int n1, int n2){            //    return n1 - n2;            //});            // Lamda表达式写法            int n = GetMax<int>(obj, (int n1, int n2) => {                return n1 - n2;            });            Console.WriteLine(n);            Console.ReadKey();        }        public static T GetMax<T>(T[] obj, Compare<T> del)        {            T max = obj[0];            for (int i = 0; i < obj.Length; i++)            {                if (del(obj[i], max) > 0)                {                     max = obj[i];                }            }            return max;        }    }}


0 0
原创粉丝点击