求最大的数(四):泛型委托

来源:互联网 发布:微云直链解析php源码 编辑:程序博客网 时间:2024/06/16 05:12

一 : 泛型委托



二  代码

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml;namespace CsharpConsoleApplication{    public delegate bool MyMaxObjDelegate<T>(T max,T obj);    class Program    {        static void Main(string[] args)        {            object objMax;            //求整形数组里最大的整数           int[] num = {3,8,2,13,5,21};//这里 不需要定义成object数组了,因为用了泛型           objMax = GetMax(num, GetMaxInt);           System.Console.WriteLine("数组里最大的整数: "+ (int)objMax);            //求学生里分数最高的学生的名字           STUDENT[] stu = { new STUDENT() { name = "小明", score = 98 }, new STUDENT() { name = "胖子", score = 78 }, new STUDENT() { name = "大头", score = 88 } };           objMax = GetMax(stu, GetMaxStudent);           System.Console.WriteLine("学生里分数最高的名字: " + ((STUDENT)objMax).name);           System.Console.ReadLine();        }        static public T GetMax<T>(T[] obj, MyMaxObjDelegate<T> del)  //泛型        {            T objMax = obj[0];            int i = 0 ;            for( i= 0 ; i<obj.Length ; i++)            {                if (del(objMax, obj[i]))                {                    objMax = obj[i];                }            }            return objMax;        }        static public bool GetMaxInt(int max,int num)        {            bool flag = false;            if (max < num)            {                flag = true;            }                return flag;        }        static public bool GetMaxStudent(STUDENT max, STUDENT stu)        {            bool flag = false;            if ( max.score  < stu.score )            {                flag = true;            }            return flag;        }         }    class STUDENT    {        public string name { get; set; }        public int score { get; set; }    }}


三  为什么要用泛型:

避免拆箱装箱



0 0
原创粉丝点击