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
- C#学习笔记之泛型委托
- C#学习笔记之委托
- C#学习笔记-委托
- C#学习笔记 委托
- 【C#学习笔记】--委托
- C#学习笔记-委托
- C#之委托学习
- C#学习之委托
- C#学习之委托
- C#学习之----委托
- 学习笔记之----委托
- 学习笔记之---C#中的委托与事件
- 新手菜鸟学习C#的笔记总结 之委托
- C#学习笔记之委托的各种写法
- C#学习笔记之——委托(delegate)
- C#学习笔记-delegate 委托
- c#学习笔记(六)委托
- C#学习笔记五---委托
- 购物车复选,oc版地区选择器
- 内部类
- servlet与jsp区别
- Django admin list_display学习
- MFC 树控件遍历
- C#学习笔记之泛型委托
- C语言位运算
- dfsdfd
- 创建型--单例模式
- AngularJS实例教程(二)
- 工作总结
- python 利用文件锁单例执行脚本
- GBK和UTF8的区别
- HttpURLConnection