WEB开发网
开发学院软件开发C语言 Effective C# 原则26:用IComparable和IComparer实... 阅读

Effective C# 原则26:用IComparable和IComparer实现对象的顺序关系

 2009-02-19 08:16:22 来源:WEB开发网   
核心提示: Customer c1;Employee e1;if ( ( c1 as IComparable ).CompareTo( e1 )>0 )Console.WriteLine( "Customer one is greater" );当你通过隐式实现ICompar

Customer c1;
Employee e1;
if ( ( c1 as IComparable ).CompareTo( e1 ) > 0 )
 Console.WriteLine( "Customer one is greater" );

当你通过隐式实现IComparable接口而又提供了一个类型安全的比较时,重载版本的强类型比较增加了性能,而且减少了其他人误用CompareTo方法的可能。你还不能看到.Net框架里Sort函数的所有好处,这是因为它还是用接口指针(参见原则19)来访问CompareTo()方法,但在已道两个对象的类型时,代码的性能会好一些。

我们再对Customer 结构做一个小的修改,C#语言可以重载标准的关系运算符,这些应该利用类型安全的CompareTo()方法:

public struct Customer : IComparable
{
 private string _name;
 public Customer( string name )
 {
  _name = name;
 }
 #region IComparable Members
 // IComparable.CompareTo()
 // This is not type safe. The runtime type
 // of the right parameter must be checked.
 int IComparable.CompareTo( object right )
 {
  if ( ! ( right is Customer ) )
   throw new ArgumentException( "Argument not a customer",
    "right");
  Customer rightCustomer = ( Customer )right;
  return CompareTo( rightCustomer );
 }
 // type-safe CompareTo.
 // Right is a customer, or derived from Customer.
 public int CompareTo( Customer right )
 {
  return _name.CompareTo( right._name );
 }
 // Relational Operators.
 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;
 }
 #endregion
}

上一页  1 2 3 4  下一页

Tags:Effective 原则 IComparable

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接