打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
用IComparable和IComparable<T>接口实现两个类对象的比较大小.

1.IComparable接口

namespace System
{
    public interface IComparable
    {
         //Less than zero This instance is less than obj. 
         //Zero This instance is equal to obj. 
         //Greater than zero This instance is greater than obj.
         int CompareTo(object obj);
    }
}

2.一个example

namespace ConsoleApplicationCompare
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student();
            Student s2 = new Student();

            s1.Name = "张三";
            s2.Name = "张三";

            s1.Score = 112;
            s2.Score = 211;

            Console.WriteLine(((IComparable)s1).CompareTo(s2));

            Console.ReadKey();
        }       
    }

    public class Student: IComparable
    {
        public string Name { set; get; }
        public int Score { set; get; }

        public int CompareTo(object obj)
        {
            int result = 0;

            Student o = (Student)obj;
            if (this.Score > o.Score)
                result = 1;
            else if (this.Score == o.Score)
                result = 0;
            else
                result = -1;

            return result;
        }

    }
}

 

3.IComparable<T>接口

namespace System
{
    // Type parameters: T: The type of objects to compare. That  is, you can use either the type you specified or any type that is less derived.
    public interface IComparable<in T>
    {
        int CompareTo(T other);
    }
}

 

4. example 第二版

namespace ConsoleApplicationCompareT
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student();
            Student s2 = new Student();

            s1.Name = "张三";
            s2.Name = "张三";

            s1.Score = 112;
            s2.Score = 211;

            Console.WriteLine(s1.CompareTo(s2));

            Console.ReadKey();
        }
    }

    public class Student : IComparable<Student>
    {
        public string Name { set; get; }
        public int Score { set; get; }

        public int CompareTo(Student obj)
        {
            int result = 0;

            if (this.Score > obj.Score)
                result = 1;
            else if (this.Score == obj.Score)
                result = 0;
            else
                result = -1;

            return result;
        }

    }
}

 

5.结论

泛型接口更好用, it's obvious.

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
显示实现接口
C# 中的IComparable和IComparer
Net编程接口剖析系列之比较和排序 (IComparable和IComparer)
c#对象排序
c# 接口代码实例
C# Class ArrayList 多維陣列 排序- 藍色小舖 BlueShop
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服