c#委托的定义理解

含义:

  (1) 从数据结构来讲,委托是和类一样是一种用户自定义类型。

   (2) 从设计模式来讲,委托(类)提供了方法(对象)的抽象。

既然委托是一种类型,那么它存储的是什么数据?

我们知道,委托是方法的抽象,它存储的就是一系列具有相同签名和返回回类型的方法的地址。调用委托的时候,委托包含的所有方法将被执行

Demo

废话不多说,上Demo

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApp1
 7 {
 8     internal class Program
 9     {
10         static void Main(string[] args)
11         {
12             object objMax;
13             int[] ints = { 1, 89, 3, 7, 10 };
14             //获取int类型最大值
15             objMax = GetMax<int>(ints, (x, y) => x < y);
16             Console.WriteLine(objMax);
17             Person[] people = { new Person("baidu", 10), new Person("ali", 67), new Person("qq", 11) };
18             //获取自定义类最大值
19             objMax = GetMax<Person>(people, (p1, p2) => p1.Age < p2.Age);
20             Console.WriteLine(objMax.ToString());
21             string[] strings = new string[] { "test", "jack-like", "angle", "weituo" };
22             //获取字符串类型最大值
23             objMax = GetMax<string>(strings, (s1, s2) => s1.Length < s2.Length);
24             Console.WriteLine(objMax);
25             Console.ReadKey();
26         }
27 
28 
29         /// <summary>
30         /// 获取最大数
31         /// </summary>
32         /// <typeparam name="T">泛型类型</typeparam>
33         /// <param name="ts">泛型数组</param>
34         /// <param name="func">泛型委托</param>
35         /// <returns></returns>
36         public static T GetMax<T>(T[] ts, Func<T, T, bool> func)
37         {
38             T max = ts[0];
39             for (int i = 1; i < ts.Length; i++)
40             {
41                 if (func(max, ts[i]))
42                 {
43                     max = ts[i];
44                 }
45             }
46             return max;
47         }
48 
49 
50     }
51     public class Person
52     {
53         public Person(string name, int age)
54         {
55             Name = name;
56             Age = age;
57         }
58         public int id { get; set; }
59         public string Name { get; set; }
60         public int Age { get; set; }
61         public override string ToString()
62         {
63             return "name=" + Name + ",age=" + Age;
64         }
65     }
66 }
View Code

 

posted @ 2022-04-06 08:32  QueryWord  阅读(143)  评论(0编辑  收藏  举报