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

本文介绍了一种通过委托实现的通用方法,该方法能够根据不同类型的输入数据(如整数数组或学生对象数组)找到其中的最大值。示例中包括了求整数数组中的最大值及学生对象数组中分数最高的学生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

利用委托


二 : 代码

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; }
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值