c# 泛型委托

泛型委托

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

namespace _09泛型委托
{
    //限定比较的条件
    public delegate int DelCompare<T>(T t1, T t2);//泛型委托
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
            string[] names = { "张三", "李FatSoFat shit", "王五" };

            Person[] pers = { new Person() { Name = "张三", Age = 19 }, new Person() { Name = "李四", Age = 20 }, new Person() { Name = "王五", Age = 22 } };



            string max1 = GetMax<string>(names, (s1, s2) => { return s1.Length - s2.Length; });
            int max2 = GetMax<int>(nums, (n1, n2) => { return n1 - n2; });
            Person max3 = GetMax<Person>(pers, (p1, p2) => { return p1.Age - p2.Age; });
            Console.WriteLine(max1);
            Console.WriteLine(max2);
            Console.WriteLine(max3.Age);
            Console.ReadKey();

        }

        static T GetMax<T>(T[] nums, DelCompare<T> del)//外面传进来一个比较的方式
        {
            T max = nums[0];
            for (int i = 0; i < nums.Length; i++)
            {
                //委托 : max-nums[i]
                if (del(max, nums[i]) < 0)//比较的方式 if(nums[i]>max)
                {
                    max = nums[i];
                }
            }
            return max;
        }
    }
    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
}

 

posted on 2017-06-13 15:47  算顺网  阅读(177)  评论(0编辑  收藏  举报

导航