泛型委托

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型委托
{
    public delegate int DelCompare<T>(T t1, T t2);
    // public delegate int DelCompare(object o1, object o2);
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3, 4, 5 };
            int max = GetMax<int>(nums, Compare1);//第一个参数是Object sender,第二个参数是BoiledEventArgs e,这里没有用event事件封装delegate委托,直接传方法作委托参数
            Console.WriteLine(max);

            string[] names = { "abcdefg", "fdsfds", "fdsfdsfdsfdsfdsfdsfdsfsd" };
            string max1 = GetMax<string>(names, (string s1, string s2) =>//lamda表达式,可以理解成匿名函数的另一种写法
            {
                return s1.Length - s2.Length;
            });
            Console.WriteLine(max1);
            Console.ReadKey();
        }
        public static T GetMax<T>(T[] nums, DelCompare<T> del)
        {
            T max = nums[0];
            for (int i = 0; i < nums.Length; i++)
            {

                if (del(max, nums[i]) < 0)//if的括号里面del(max, nums[i])是直接调用运行委托对象,给委托传参(max, nums[i]),等价于传入并调用Compare1()方法
                {
                    max = nums[i];
                }
            }
            return max;
        }


        public static int Compare1(int n1, int n2)//这个方法只能用于比较泛型的T为int的情况,换另一种Type就必须另外写方法
        {
            return n1 - n2;
        }
    }
}
原文地址:https://www.cnblogs.com/blacop/p/5998621.html