The IComparable and Icompare interfaces are a standard way of comparing objects in the. NET Framework, which provides a comparison method with similar return values (greater than 0 equals 0 less than 0), with the following differences:1. IComparable is implemented in the class of the object to compare, you can compare the object and another object. 2. IComparer is implemented in a separate class and can compare any two objects. First look at IComparable this interface method isintCompareTo (ObjectOBJ); Method has only one parameter, we know that the comparison must have at least two objects, so this method can only be applied to the object class to be compared, and the object passed by the parameter can be Thismake comparisons. classObj:icomparable<obj>{ Public intAge =Ten; Public intCompareTo (obj other) {//return This.age.CompareTo (other.age); //The following code is a concrete implementation of this method if( This. Age = =other.age) {return 0; } Else if( This. Age >other.age) {return 1; } Else { return-1; } }}Static voidMain (string[] args) {obj a=Newobj (); Obj b=Newobj (); A.compareto (b); //0A.age= -; A.compareto (b); //1A.age=5; A.compareto (b); //-1}
The interface IComparable is mainly to implement the comparison rules between the class objects. Look at IComparer. This interface provides a method that requires two parameters, which is also a comparison operation, but the main purpose is to sort the objects instead of adding comparison operations to the classes. classobj{ Public intAge =Ten;}classObjcomp:icomparer<obj>{ Public intCompare (obj x, obj y) {//return X.age.compareto (y.age); //The following code is a concrete implementation of this method if(X.age = =y.age) {return 0; } Else if(X.age >y.age) {return 1; } Else { return-1; } }}Static voidMain (string[] args) {List<obj> list =NewList<obj>(); List. ADD (NewObj () {age = - }); List. ADD (NewObj () {age = - }); List. ADD (NewObj () {age = + }); //the original order of elements in the list (by age) 50,20,40list. Sort (NewObjcomp ());//Public void Sort (icomparer<t> comparer); Call the overloaded version of the Sort method//order of elements in sorted list (by age) 20,40,50of course, if you want to change the collation in descending order you can swap the return value of the method parameter's age value greater than and less than Objcomp.
Comparison and ordering of objects: IComparable and IComparer interfaces