IComparable、IComparer接口

C#中,自定义类型,支持比较和排序,需要实现IComparable接口。IComparable接口存在一个名为CompareTo()的方法,接收类型为object的参数表示被比较对象,返回整型值:1表示当前对象大于被比较对象,0表示两者相等,-1表示当前对象小于被比较对象。

IComparable接口:

public int CompareTo(object o) {}

IComparer接口:(比较器

若想以更加灵活的方式对自定义类进行比较,可以声明一个继承自IComparer接口的比较器,实现接口方法Comprae(),接收2个object类型参数作为比较对象,返回整型值:1表示前者大于后者,0表示两者相等,-1表示前者小于后者。

public int Compare(object x, object y) {}

IComparable是“可比较的”意思,自定义类实现该接口,就具有可比较的功能;IComparer是“比较器”的意思,实现该接口的类就是一个比较器,可以将比较器“注入”类中,使类具有比较和排序的功能。

IComparable接口示例代码

定义学生类,该类实现IComparable接口的CompareTo方法,该方法对Age 进行大小比较。

复制代码
 1     public class Student : IComparable
 2     {
 3         public string Name { get; set; }
 4         public string Sex { get; set; }
 5         public int Age { get; set; }
 6         public int CompareTo(object obj)
 7         {
 8             Student stu = obj as Student;
 9             if (Age > stu.Age)
10             {
11                 return 1;
12             }
13             else if (Age == stu.Age)
14             {
15                 return 0;
16             }
17             else
18             {
19                 return -1;
20             }
21         }
22     }
复制代码

调用List<T>.Sort方法实现stuList按照学生的年龄来排序。

复制代码
 1         static void Main(string[] args)
 2         {
 3             List<Student> stuList = new List<Student>();
 4             stuList.Add(new Student() { Name = "tiana0", Sex = "Man", Age = 18 });
 5             stuList.Add(new Student() { Name = "tiana1", Sex = "Woman", Age = 20 });
 6             stuList.Add(new Student() { Name = "tiana2", Sex = "Woman", Age = 16 });
 7             stuList.Add(new Student() { Name = "tiana3", Sex = "Man", Age = 21 });
 8             stuList.Add(new Student() { Name = "tiana4", Sex = "Woman", Age = 19 });
 9             stuList.Sort();
10             foreach (Student stu in stuList)
11             {
12                 Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age);
13             }
14         }
复制代码

IComparer接口示例代码

定义学生类。

 public class Student
    {
        public string Name { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
    }

自定义比较器AgeComparer,实现接口IComparer<Student>,对学生年龄进行比较。

    public class AgeComparer : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return x.Age.CompareTo(y.Age);
        }
    }

自定义比较器NameComparer,实现接口IComparer<Student>,对学生姓名进行比较。

public class NameComparer : IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }

调用List<T>.Sort方法实现stuList按照学生的年龄与姓名排序。

复制代码
 1         static void Main(string[] args)
 2         {
 3             List<Student> stuList = new List<Student>();
 4             stuList.Add(new Student() { Name = "aki", Sex = "Man", Age = 18 });
 5             stuList.Add(new Student() { Name = "cki", Sex = "Woman", Age = 20 });
 6             stuList.Add(new Student() { Name = "dki", Sex = "Woman", Age = 16 });
 7             stuList.Add(new Student() { Name = "bki", Sex = "Man", Age = 21 });
 8             stuList.Add(new Student() { Name = "fki", Sex = "Woman", Age = 19 });
 9             stuList.Sort(new AgeComparer());
10             Console.WriteLine("按照年龄排序:");
11             foreach (Student stu in stuList)
12             {
13                 Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age);
14             }
15             stuList.Sort(new NameComparer());
16             Console.WriteLine();
17             Console.WriteLine("按照名称排序:");
18             foreach (Student stu in stuList)
19             {
20                 Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age);
21             }
22         }
复制代码

 



posted @   .Neterr  阅读(291)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示