实现CompareTo() - 通过各种函数进行比较

时间:2017-01-31 15:12:51

标签: c# compare compareto

我实现了CompareTo(),如此:

 public override int CompareTo(object obj)
 {
   //quick failsafe
   MyClass other;
   if (obj is MyClass)
   {
     other = obj as MyClass;
   }
   else 
   { 
     return 1; 
   }
   //now we should have another comparable object.
   /*
    * 1: this is greater.
    * 0: equals.
    * -1: this is less.  
    */
   if (other.GetValue() < this.GetValue())
   {
     // this is bigger
     return 1;
   }
   else if (other.GetValue() > this.GetValue())
   {
     //this is smaller
     return -1;
   }
   else 
   { 
     return 0; 
   }
}

但是,当我想选择函数GetValue()时,事情变得有趣。我为此设置了几个:Average()Best()CorrectedAverage()Median()。顺便说一下,我通过floats数组进行比较。事实是,我不想在我在这个课程中定义的switch-case上使用enum来告诉你要点什么。有没有一种方法可以决定哪个功能要好看又干净?

1 个答案:

答案 0 :(得分:2)

鉴于你的班级有很多不同的比较方法,几乎​​可以肯定不应该实现IComparable

相反,为每种不同的比较对象的方式创建IComparer<T>个实例。想要比较该类型实例的人可以选择使用最适合他们情况的比较的比较器。