委托

1.为什么要使用委托

将一个方法传递给另一个方法。

2.委托概念

委托所指向的函数必须跟委托具有相同的签名(参数+返回值)

3.求任意数组的最大值(匿名函数+泛型委托)

 1     //声明一个委托
 2     public delegate int DelCompare<T>(T t1,T t2);
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //int数组
 8             int[] nums = { 1, 2, 3, 4, 5 };
 9             int maxInt = GetMax<int>(nums, (int t1, int t2) =>
10             {
11                 return t1 - t2;
12             });
13             Console.WriteLine(maxInt);
14             Console.ReadKey();//按Enter继续
15             
16             //字符串数组
17             string[] strs = { "abcdef", "hijklmnopq", "rstuvwxyzqweasdzxc" };
18             string maxStr = GetMax<string>(strs, (string s1, string s2) =>
19             {
20                 return s1.Length - s2.Length;
21             });
22             Console.WriteLine(maxStr);
23             Console.ReadKey();
24         }
25 
26         /// <summary>
27         /// 求任意数组最大值
28         /// </summary>
29         /// <typeparam name="T">任意类型</typeparam>
30         /// <param name="nums">任意数组</param>
31         /// <param name="del">委托</param>
32         /// <returns></returns>
33         public static T GetMax<T>(T[] nums,DelCompare<T> del)
34         {
35             T max = nums[0];
36             for (int i = 0; i < nums.Length; i++)
37             {
38                 //要传入一个比较的方法
39                 if (del(max, nums[i]) < 0)
40                 {
41                     max = nums[i];
42                 }
43             }
44             return max;
45         }
46     }
View Code

  结果:

  

4.lamda表达式(=> :相当于 goes to,箭头左边是参数,右边是方法体)

1             List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
2             list.RemoveAll(n => n > 4);//删除大于 4 的所有元素
3             foreach (var item in list)
4             {
5                 Console.WriteLine(item);
6             }
7             Console.ReadKey();
View Code

  结果:

  

5.多播委托

 1     // 声明一个委托指向一个函数
 2     public delegate void DelTest();
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             DelTest del = T1;//指向T1
 8             del += T2;
 9             del();//调用委托
10             Console.ReadKey();
11         }
12             
13         public static void T1()
14         {
15             Console.WriteLine("我是T1");
16         }
17         public static void T2()
18         {
19             Console.WriteLine("我是T2");
20         }
21     }
View Code

  结果:

  

 

算是对自己学委托的总结吧!

以上。

posted @ 2019-08-05 21:59  指尖上的生产者  阅读(248)  评论(0编辑  收藏  举报