IComparable vs IComparer

       They have a variety of uses, but perhaps the most common is in sorting an
ArrayList.
       Suppose you have a class Dog, and an ArrayList, List, of Dogs. You wish to
sort List by ageOfDog. You would have Dog implement the interface
IComparable. The implementation would cast the parameter in the CompareTo
method to a Dog, and return a value based on how this.ageOfDog compared to
((Dog)(obj)).ageOfDog). Then to sort the List, you could just invoke
List.Sort().
      But suppose in another part of the application you would like to sort the
same List by nameOfDog. You have already "used up" the IComparable
interface that Sort uses. So, you can either set up a new class that
inherits from IComparer, or (if this is the only additional sort you need),
have Dog implement the IComparer interface too.
     Then in the Compare method, which has two parameters, you would cast each to
a Dog and return a value based upon how the nameOfDog compares. Then to
invoke a sort by nameOfDog you would just say List.Sort(this) (or
List.Sort(someObjectThatImplementsIComparer)).
posted @ 2008-04-26 22:33  debugzhu  阅读(458)  评论(2编辑  收藏  举报