求最大的数(二):利用委托改成一个入口函数

来源:互联网 发布:俄罗斯聊天软件下载 编辑:程序博客网 时间:2024/06/05 00:38

一 :求数组里最大的整数和求学生里分数最高的学生如何改成一个函数入口?

利用委托


二 : 代码

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 object MyMaxObjDelegate(object[] obj);    class Program    {        static void Main(string[] args)        {            object objMax;            //求整形数组里最大的整数           object[] num = {3,8,2,13,5,21};//这里要定义成object数组,因为int 数组不能 赋值给 object 数组           objMax = GetMax(num, GetMaxInt);           System.Console.WriteLine("数组里最大的数是: " + (int)objMax);            //求学生里分数最高的学生的名字           object[] 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 object GetMax(Object[] obj, MyMaxObjDelegate del)        {            object objMax = null;            objMax = del(obj);            return objMax;        }        static public object GetMaxInt(object[] num)        {            int i = 0 ;            int max = (int)num[0];            for (i = 0; i < num.Length; i++)            {                if (max < (int)num[i])                {                    max = (int)num[i];                }            }                return max;        }        static public STUDENT GetMaxStudent(object[] stu)        {            int i = 0;            STUDENT max = (STUDENT)stu[0];            for(i = 0 ; i< stu.Length ; i++)            {                if (max.score < ((STUDENT)stu[i]).score)                {                    max = (STUDENT)stu[i];                }            }            return max;        }         }    class STUDENT    {        public string name { get; set; }        public int score { get; set; }    }}




0 0
原创粉丝点击