|  | 网站首页 | .Net研究 | 
您现在的位置: 程序员之路 >> .Net研究 >> 相关资讯 >> 学习体会 >> 文章正文
赞助商链接
频 道 导 航
.Net研究频道栏目导航
相 关 文 章
Effective C# Item 26: Implement Ordering Relations           
Effective C# Item 26: Implement Ordering Relations
作者:aiyagaze 文章来源:不详 更新时间:2007-5-10 11:53:28

Effective C# Item 26: Implement Ordering Relations with IComparable and IComparer

Effective C# Item 26: Implement Ordering Relations with IComparable and IComparer

      有时候我们需要为类定义排序关系以便在集合中对该类的对象进行排序和检索。在.Net Framework中定义了两种用来描述排序顺序关系的接口:IComparable和IComparer。IComparable接口描述了类型的通用排序比较方法,而IComparer描述的是两个对象之间的比较方法。在本节中主要讨论如何实现这种排序顺序关系。另外,我们可以通过实现自定义关系运算符来提供这些特殊的比较关系。

      IComparable接口包含一个方法:CompareTo()。这个方法的历史可以追溯到C语言类库中的strcmp函数:如果当前对象小于比较对象则返回小于0的值,如果相等则返回0,如果当前对象大于比较对象则返回大于0的值。IComparable的参数为System.Object型,因此我们在使用的时候需要对参数的类型进行检查:

    public struct Customer : IComparable
    
{
        
private readonly string _name;
        
public string Name
        
{
            
get
            
{
                
return _name;
            }

        }


        
public Customer(string name)
        
{
            _name 
= name;
        }


        
IComparable 成员
文章录入:admin    责任编辑:admin 
  • 上一篇文章:

  • 下一篇文章:
  • .Net研究栏目导航
    网站频道导航