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

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

 2009-02-19 08:16:22 来源:WEB开发网   
核心提示: public struct Customer : IComparable{private string _name;public Customer( string name ){_name = name;}#region IComparable Members// IComparable.

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 );
 }
 #endregion
}

现在,IComparable.CompareTo()就是一个隐式的接口实现,它只能通过IComparable 接口的引用才能调用。你的用户则只能使用一个类型安全的调用,而且不安全的比较是不可能访问的。下面这样无意的错误就不能通过编译了:

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

这不能通过编译,因为对于公共的Customer.CompareTo(Customer right)方法在参数上不匹配,而IComparable. CompareTo(object right)方法又不可访问,因此,你只能通过强制转化为IComparable 接口后才能访问:

上一页  1 2 3 4  下一页

Tags:Effective 原则 IComparable

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