C#通过接口 继承接口的类 实现约束 对List内数据类型的值进行排序,可直接复制使用

工具类

通过接口 继承接口的类 实现约束 对List内数据类型的值进行排序,可直接复制使用

复制代码
 //工具类 Tools
 //说明接口的
 //1.先有接口 2.继承接口的类 3.实现约束
 public interface IComParable<T>            //接口
 {
     int ComPareTo(T other);                //在list的数组中,想对几种数据进行排列,就要写几个方法
                                            //这里以一种数据举例
 }
 public class Person : IComParable<Person>  //继承接口的类
 {
     public string Name { get; set; }
     public int Age { get; set; }
     public Person(string name, int age)
     {
         Name = name;
         Age = age;
     }
     //实现接口的方法
     public int ComPareTo(Person other)     //实现接口的方法
     {
         if(other == null) return 1;
         return this.Age.CompareTo(other.Age);
     }
     //重写Tostring方便打印
     public override string ToString()
     {
         return $"{Name}:{Age} years old";
     }
 }
 //使用接口约束
 internal class MyComparer<T>where T:IComParable<T>
 {
     //比较:两个对象
     public bool IsGreater(T x,T y)
     {
         //原则意义上来说,T如果是对象,那么是没有办法比较的,但是当前对象中因为有从接口实现的比较方法,在内部是对Age进行的比较,所以这里x和y能够进行比较
         //注意,这里的x和y必须是Person的对象
         return x.ComPareTo(y) > 0;
     }
     //对列表进行排序
     public void Sort(List<T> list)
     {
         //Sort可以立即为只能对值类型的数据进行比较,没办法比较复杂类型
         list.Sort((x, y) => x.ComPareTo(y));
     }
 }
复制代码
MyComparer<Person> myComparer = new MyComparer<Person>(); //将接口约束实例化
List<Person> list = new List<Person>        //向Person中添加数据并将其添加到List中
{
    new Person("Alice",40),
    new Person("Bob",28),
    new Person("David",35),
    new Person("Eva",18),
};
//使用自己封装的泛型方法排序
myComparer.Sort(list);                      //使用接口约束中的对列表排序的方法
Console.WriteLine("排序过后");
foreach (var item in list)
{
    Console.WriteLine(item);                //使用Foreach进行遍历
    
}
相关推荐
二进制person37 分钟前
Java SE--方法的使用
java·开发语言·算法
OneQ6661 小时前
C++讲解---创建日期类
开发语言·c++·算法
码农不惑2 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
Coding小公仔3 小时前
C++ bitset 模板类
开发语言·c++
小赖同学啊4 小时前
物联网数据安全区块链服务
开发语言·python·区块链
shimly1234564 小时前
bash 脚本比较 100 个程序运行时间,精确到毫秒,脚本
开发语言·chrome·bash
葬歌倾城4 小时前
JSON的缩进格式方式和紧凑格式方式
c#·json
IT_10244 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
new_zhou5 小时前
Windows qt打包编译好的程序
开发语言·windows·qt·打包程序