static void Main (string[] args)
        {
        	//传入一个学生集合
            Stu[] s = new Stu[]
            {
                new Stu{ ID = 1,Name = "张三",Age = 19 },
                new Stu{ ID = 2,Name = "李四",Age = 20 },
                new Stu{ ID = 3,Name = "王五",Age = 18 }

            };
			//调用泛型冒泡排序
            var n = sort<Stu>(s);
			//遍历输出排序后的学生姓名
            foreach (var item in n)
            {
                Console.WriteLine(item.Name); 
            }

            Console.ReadKey();
        }

        //泛型数组 冒泡排序
        static T[] sort<T>(T[] x) where T:IComparable<T>
        {
            T b = default(T);
            for (int i = 0; i < x.Length-1; i++)
            {
                for (int j = 0; j < x.Length-i-1; j++)
                {
                    if (x[j].CompareTo(x[j+1])<0)
                    {
                        b = x[j];
                        x[j] = x[j + 1];
                        x[j + 1] = b;
                    }
                }
            }
            return x;
        }
		//继承接口
        public class Stu:IComparable<Stu>
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }

            public int CompareTo(Stu other)
            {
            	//根据年龄来排序
                return this.Age.CompareTo(other.Age);
            }
        }
posted on 2019-11-06 20:07  .net之路  阅读(70)  评论(0编辑  收藏  举报