在LinkedList <t> </t>中搜索

时间:2010-10-16 05:54:30

标签: c# interface

我们有这个代码:

class student :IComparable , IComparable<student> 
{
    public string name = "";

    public override string ToString()
    {
        return name; 
    }

    #region IComparable Members

    public int CompareTo(object obj)
    {
        if (this.name.Equals(((student)obj).name ) )
            return 0 ; 
        else
            return -1 ; 
    }

    #endregion

    #region IComparable<student> Members

    public int CompareTo(student other)
    {
        if (this.name.Equals (other.name )) 
            return 0 ; 
        else
            return -1 ; 
    }

    #endregion
}

我在Main Like中创建了这个类的LinkedList:

LinkedList<student> list = new LinkedList<student>(); 
list.AddLast(new student { name="Farah"}); 
list.AddLast(new student { name="Noor"}); 
list.AddLast(new student { name="Reem"});

foreach (student s in list)
{
    Console.WriteLine(s);
}

它的印刷品: 法拉 努尔 REEM

但是当我尝试搜索任何没有找到它的元素时,例如:

Console.WriteLine(list.Contains(new student{ name="Noor"})); 

这个打印假,虽然“学生”类实现“IComparable,IComparable”!!

我该怎么做才能工作?

2 个答案:

答案 0 :(得分:2)

问题,Contains不适用于IComparable接口。它使用Equals方法。所以覆盖它:

    public override bool Equals(object obj)
    {
        return this.CompareTo(((IComparable)obj)) == 0;
    }

答案 1 :(得分:1)