C#中的LinkedList的Find()方法适用于字符串等,但如何将它与结构,对象等一起使用?
这是我的代码:
{
LinkedList<Item> TestLinkedList = new LinkedList<Item>();
TestLinkedList.AddFirst(new Item(3, "Head n Shoulders"));
TestLinkedList.AddAfter(TestLinkedList.First, new Item(45, "Dell"));
//Get the 2nd node in the linklist
Item c = new Item(3, "Head n Shoulders");
LinkedListNode<Item> Node2 = TestLinkedList.Find(c);
TestLinkedList.AddAfter((Node2), new Item(32, "Adidas"));
foreach (Item i in TestLinkedList)
{
i.Print();
}
Console.ReadKey();
}
它为Node2返回NULL。我在不使用独特的Hashcode等时犯了错误吗?
答案 0 :(得分:2)
为了让Find
返回正确的对象,您的Item
类需要覆盖Equals
方法。当然,您还需要覆盖GetHashCode
:虽然Find
的{{1}}没有调用LinkedList
,但这两种方法需要一起更改:
覆盖
GetHashCode
的类型也必须覆盖Equals(Object)
;否则,哈希表可能无法正常工作。