通过实现System.IComparable接口的CompareTo方法对两个类进行比较

假设现在有一个学生类

 class Student 
    {
        int age;
        public Student(int age)
        {
            this.age = age;
        }
   }

要使学生类之间能进行比较,实现System.IComparable接口的CompareTo方法

 class Student : System.IComparable
    {
        int age;
        public Student(int age)
        {
            this.age = age;
        }
 public int CompareTo(object obj)
        {
            Student stu = (Student)obj;
            if (this.age > stu.age)
                return 1;
            else if (this.age == stu.age)
                return 0;
            else
                return -1;
        }
    }

这样即可以比较两个类

1             Student xiaomin = new Student(20);
2             Student xiaohong = new Student(15);
3             if (xiaomin.CompareTo(xiaohong) > 0)
4                 Console.WriteLine("小明比小红大");
5             else
6                 Console.WriteLine("小明不比小红大");        

研究一下System.IComparable接口,就会发现它的参数被定义成一个object。
然而这种方式不是类型安全的,
因为可能传进去的不是Student类型,就出报错
为了确保类型安全,应使用System.命名空间中定义的泛型
IComparable<T>接口,它定义了以下方法:
int CompareTo(T other);
方法获取的是类型参数T,而不是object, 所有安全得多

 1 class Student : System.IComparable<Student>
 2     {
 3         int age;
 4         public Student(int age)
 5         {
 6             this.age = age;
 7         }
 8 
 9      public int CompareTo(Student stu)
10         {
11             if (this.age > stu.age)
12                 return 1;
13             else if (this.age == stu.age)
14                 return 0;
15             else
16                 return -1;
17         }
18 }

 

转载于:https://www.cnblogs.com/zhaotianff/p/6004528.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值