C#学习 - IComparer<T> 和 IComparable<T>的区别

IComparer<T> is implemented by types that are capable of comparing 2 different values, whereas an instance of IComparable<T> is capable of comparing _itself_ with another value.

例如

        public class Employee_ClassB : IComparable<Employee_ClassB>
        {
            public Employee_ClassB() { Name = "hello from Class B"; }
            public Employee_ClassB(string Name) { this.Name = Name; }
            public string Name { get; set; }
            public int CompareTo(Employee_ClassB obj)
            {
                return Name.CompareTo(obj.Name);
            }
        }

        public class EmployeeComparer : IComparer<Employee_ClassB>
        {
            public int Compare(Employee_ClassB x, Employee_ClassB y)
            {
                return x.CompareTo(y);
            }
        }
         ...
            Employee_ClassB e1 = new Employee_ClassB("1st Instance of ClassB");
            Employee_ClassB e2 = new Employee_ClassB("2nd Instance of ClassB");
            int e_result = e1.CompareTo(e2);
            EmployeeComparer ec = new EmployeeComparer();
            int ec_result = ec.Compare(e1, e2);
 
 

猜你喜欢

转载自blog.csdn.net/jianhui_wang/article/details/79556143
今日推荐