这里我们使用泛型约束,接口,委托一起共同实现sort的工作流程
这仅仅是我自己的模拟,仅作参考
排序方法:冒泡排序(也可以使用别的,这里我就拿冒泡排来模拟)
用Student类来进行演示
using System;
using System.Collections.Generic;
namespace SortDemo
{
public class Program
{
static void Main()
{
MyList<Student> myList = new
(
new (1, 18),
new (2, 19),
new (1, 17),
new (2, 18)
);
myList.Sort();
myList.Show(Student.Show);
}
}
public class Student : IComparable<Student>
{
private int id;
private int age;
public Student(int id = 0, int age = 0)
{
this.id = id;
this.age = age;
}
public int CompareTo(Student other)
{
if (id.CompareTo(other.id) != 0) return id.CompareTo(other.id);
return age.CompareTo(other.age);
}
public static void Show(Student student)
{
Console.WriteLine("ID :" + student.id);
Console.WriteLine("Age :" + student.age);
}
}
public class MyList<T> where T : IComparable<T>
{
private List<T> list;
private int length;
public MyList(params T[] it)
{
list = new();
foreach(T item in it)
{
list.Add(item);
}
length = it.Length;
}
public void Sort()
{
for (int i = 0; i < length; i++)
for (int j = i + 1; j < length; j++)
{
if (list[j].CompareTo(list[i]) < 0)
{
T t = list[i];
list[i] = list[j];
list[j] = t;
}
}
}
public delegate void ShowHander(T student);
public void Show(ShowHander show)
{
foreach (var item in list)
{
show(item);
}
}
}
}
结果