如何实现IComparable接口?
我正在用一个类的实例填充一个数组:
BankAccount[] a; . . . a = new BankAccount[] { new BankAccount("George Smith", 500m), new BankAccount("Sid Zimmerman", 300m) };  一旦我填充这个数组,我想以平衡量对它进行sorting。 为了做到这一点,我希望能够检查每个元素是否可以使用IComparablesorting。 
 我需要使用接口来做到这一点。 到目前为止,我有以下代码: 
 public interface IComparable { decimal CompareTo(BankAccount obj); } 
但我不确定这是否是正确的解决scheme。 任何build议?
你不应该自己定义IComparable。 它已经被定义。
 相反,您需要在您的BankAccount类上实现 IComparable。 
 在定义class BankAccount ,确保它实现了IComparable接口 
 然后写入BankAccout.CompareTo来比较两个对象的余额。 
编辑
 public class BankAccount : IComparable<BankAccount> { [...] public int CompareTo(BankAccount that) { if (this.Balance > that.Balance) return -1; if (this.Balance == that.Balance) return 0; return 1; } } 
编辑2显示Jeffrey L Whitledge的好答案:
 public class BankAccount : IComparable<BankAccount> { [...] public int CompareTo(BankAccount that) { return this.Balance.CompareTo(that.Balance); } } 
 使用CompareTo的这个定义,.NET中已经存在了IComparable 
 int CompareTo(Object obj) 
你不应该创build接口 – 你应该实现它。
 public class BankAccount : IComparable { int CompareTo(Object obj) { // return Less than zero if this object // is less than the object specified by the CompareTo method. // return Zero if this object is equal to the object // specified by the CompareTo method. // return Greater than zero if this object is greater than // the object specified by the CompareTo method. } } 
你想破坏性地sorting数组吗? 也就是说,你是否想要改变数组中项目的顺序? 或者你只是想要一个特定的顺序列表的项目,而不会破坏原来的秩序?
我会build议做后者几乎总是好的。 考虑使用LINQ进行无损sorting。 (并考虑使用比“a”更有意义的variables名称。)
 BankAccount[] bankAccounts = { whatever }; var sortedByBalance = from bankAccount in bankAccounts orderby bankAccount.Balance select bankAccount; Display(sortedByBalance); 
另一种方法是使用LINQ并跳过实现IComparable:
 BankAccount[] sorted = a.OrderBy(ba => ba.Balance).ToArray(); 
 已经有IComparable<T> ,但是您应该理想地支持IComparable<T>和IComparable 。 使用内置的Comparer<T>.Default通常是一个更简单的选项。 例如, Array.Sort将接受这样的比较器。 
 如果您只需要对这些BankAccounts进行sorting,请使用如下的LINQ 
 BankAccount[] a = new BankAccount[] { new BankAccount("George Smith", 500m), new BankAccount("Sid Zimmerman", 300m) }; a = a.OrderBy(bank => bank.Balance).ToArray();