委托的学习总结(续)
来源:互联网 发布: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
- 委托的学习总结(续)
- 委托的学习总结
- 学习C#委托总结
- 学习委托(2)-------解析委托的实现机制
- 学习委托(2)-------解析委托的实现机制
- 学习委托(3)-----解析委托的实现机制续篇
- 学习委托(3)-----解析委托的实现机制续篇
- C# 的委托总结
- 委托的小总结
- 委托和事件学习总结
- 学习总结--委托和事件
- 学习委托与事件的总结,附上一个例子
- 新手菜鸟学习C#的笔记总结 之委托
- 委托的学习
- vb的委托学习
- 学习简单的委托
- 委托的学习笔记
- vb的委托学习
- hdu 1088 Write a simple HTML Browser
- HDU 3605 网络流
- 在引入layout文件的时候出现resourse not found的解决问题
- 再谈闭包-词法作用域
- npm执行无响应
- 委托的学习总结(续)
- Spring AOP的实现机制
- Linq 表达式和labmda表达式
- 笨办法学python 40
- Android缓存机制&一个缓存框架推荐
- 优秀程序员不得不知道的20个位运算技巧
- HDU - 1019 - Least Common Multiple (lcm)
- 231. Power of Two--LeetCode Record
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)