委托的学习总结(续)

来源:互联网 发布:melanmeka淘宝网 编辑:程序博客网 时间:2024/06/15 21:26

关于《3、泛型委托 》
说到了泛型委托,才真正将委托的一些作用真正表现出来。
当遇到这样的情况:定义了一个泛型方法,如求一个泛型集合中最大值,
可能你就会卡在这位置上:

        public static T GetMax<T>(List<T> list)        {            T result = list[0];            foreach (var item in list)            {                //这里就卡住了,始终还得知道T是什么类型,才好写算法                if (Convert.ToInt16(result)<Convert.ToInt16(item))//这样就死了,只能用于int                {                    result = item;                }            }            return result;        }

这时自然就应该将卡住的那地方的算法 抽离成委托。再上代码

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace TDelegate{    public delegate bool DelGetMax<T>(T a, T b);    class Program    {        static void Main(string[] args)        {            List<int> listINT = new List<int> { 1, 2, 3, 4, 5, 5, 6, 7, 2, 4, 5, 7, 8, 956, 45 };            List<DateTime> listDATETIME = new List<DateTime> {                new DateTime(2016,8,15),                new DateTime(2016,2,15),                new DateTime(2016,1,15),                new DateTime(2026,8,21),                new DateTime(2016,12,15),            };            List<string> listSTRING = new List<string> { "asdfas", "ASDFAS", "xyz", "XYZ" };            //只要是泛型集合,自己定义计算GetMax的计算方式,就可以重用上啦            int ResultInt = GetMax(listINT, (int a, int b) => { return a < b; });            Console.WriteLine("List<int>中最大值是:" + ResultInt);            DateTime ResultDatetime = GetMax(listDATETIME, (DateTime dt1, DateTime dt2) => { return dt1 < dt2; });            Console.WriteLine("List<DateTime>中最大值是:" + ResultDatetime);            string ResultString = GetMax(listSTRING, (string a, string b) => { return a.Length < b.Length; });//本想用ASCII比较的,写得太啰嗦            Console.WriteLine("List<string>中最大值是:" + ResultString);            Console.ReadKey();        }        public static T GetMax<T>(List<T> list, DelGetMax<T> getMaxCore)        {            if (list.Count == 0)            {                return default(T);            }            T result = list[0];            foreach (var item in list)            {                //这里就是得法的核心,如是object类型,还得拆箱,就为其具体类型写死一个算法。,或者写N多个重载                //委托的真正用途在这里就得到了很好的体现:                //将核心的算法抽离出来做为参数(注意:算法哦,是一个函数窝)                if (getMaxCore(result, item))                {                    result = item;                }            }            return result;        }    }}

理解后,其实泛型委托也不是什么很深奥的东西,跟泛型集合、泛型方法如出一辙地理解。

0 0
原创粉丝点击