c#泛型排序·委托

本文探讨了C#中如何使用泛型进行多类对象结构体的排序,并深入解析了委托在泛型排序中的作用,帮助读者更深入理解委托的概念。
摘要由CSDN通过智能技术生成

c#泛型排序

泛型排序用于多类对象结构体分别排序的情况,也算是进一步了解委托。

class Program
    {
        static void Main(string[] args)
        {
            Student[] stu = {
            new Student("stu1", 40),
             new Student("stu2", 50),
             new Student("stu3", 46),
            new Student("stu4", 83),
             new Student("stu5", 93),
            new Student("stu6", 29)};
            TSort<Student>(stu, Student.Compare);
            foreach (var item in stu)
            {
                Console.WriteLine(item.ToString());
            }
        }
        static private void TSort<T>(T[] tt,Func<T,T,int> compare)//委托的使用
        {//泛型冒泡排序
            for (int i = 0; i < tt.Length-1; i++)
            {
                for (int j = 0; j < tt.Length-i-1; j++)
                {
                    if (compare(tt[j],tt[j+1])>0)
                    {
                        T temp = tt[j + 1];
                        tt[j + 1] = tt[j];
                        tt[j] = temp;
                    }
                }
            }
        } 
   }
    class Student
    {//prop
        public string name { get; private set; }
        public int score { get;private set; }

        public Student(string name,int score)
        {//ctor
            this.name = name;
            this.score = score;
        }
        public override string ToString()
        {
            return name+":"+score;
        }
        static public int Compare(Student stu1,Student stu2)
        {//静态方法和非静态方法的区别,非静态方法只能通过实例化对象.调用,
            //非静态方法可通过类.调用,因而二者生命周期也不一样
            if (stu1.score<stu2.score)
            {
                return -1;
            }
            else if(stu1.score>stu2.score)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值