标签:
1..Net框架提供了接口来描述对象的顺序关系:IComparable 和IComparer。
2.IComparable 为类定义了自然顺序,实现IComparer接口的类可以描述其它可选的顺序
3.原因:避免在运行时默认比较关系的低效
4.IComparable接口只有一个方法:CompareTo() ,建议进行如下的实现而不是实现一个Compareto公共方法接受的却是object类型参数,因为这样会不停的装箱拆箱
注意:IComparable.CompareTo()是一个隐式的接口实现它,只能通过IComparable 接口的引用才能调用
public struct Customer : IComparable {
private string _name; public Customer( string name ) { _name = name; } int IComparable.CompareTo( object right ) { if ( ! ( right is Customer ) ) throw new ArgumentException( "Argument not a customer", "right" );
Customer rightCustomer = ( Customer )right; return CompareTo( rightCustomer ); } public int CompareTo( Customer right ) { return _name.CompareTo( right._name ); }
}
//作者建议重写比较运算符
public static bool operator < ( Customer left, Customer right ) { return left.CompareTo( right ) < 0; }
public static bool operator <=( Customer left, Customer right ) { return left.CompareTo( right ) <= 0; }
public static bool operator >( Customer left, Customer right ) { return left.CompareTo( right ) > 0; }
public static bool operator >=( Customer left, Customer right ) { return left.CompareTo( right ) >= 0; }
EffectiveC#18--用IComparable和IComparer实现对象的顺序关系
标签:
原文地址:http://www.cnblogs.com/tiantianle/p/4951519.html