這不能通過編譯,因 為對於公共的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
}