程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Effective C#原則26:用IComparable和IComparer實現對象的順序關系(2)

Effective C#原則26:用IComparable和IComparer實現對象的順序關系(2)

編輯:關於C語言

這不能通過編譯,因 為對於公共的Customer.CompareTo(Customer right)方法在參數上不匹配,而 IComparable. CompareTo(object right)方法又不可訪問,因此,你只能通過強 制轉化為IComparable 接口後才能訪問:

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. 下一頁:
Copyright © 程式師世界 All Rights Reserved