1
讓我們有這樣的代碼:搜索<T>
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
}
我是從這個類中主要像創建的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"}));
This Print false雖然「學生」類實現了「IComparable,IComparable」!
我應該怎麼做?
爲什麼要轉換成'IComparable'? – dalle 2010-10-16 06:55:15
@dalle - 只是爲了使戲劇性的口音:) – Dewfy 2010-10-17 10:49:34
鑄造'學生'會更合適,並節省一小部分的指示。 – dalle 2010-10-17 14:37:34