【发布时间】:2016-03-31 06:47:13
【问题描述】:
尝试在 C# 中实现一个简单的单链表时,我注意到 == 在比较两个用 int 值装箱的对象类型变量时不起作用,但 .Equals 起作用。
想看看为什么会这样。
下面的sn-p是一个通用的对象类型Data属性
public class Node {
/// <summary>
/// Data contained in the node
/// </summary>
private object Data { get; set; };
}
下面的代码遍历单链表,搜索object类型的值-
/// <summary>
/// <param name="d">Data to be searched in all the nodes of a singly linked list
/// Traverses through each node of a singly linked list and searches for an element
/// <returns>Node if the searched element exists else null </returns>
public Node Search(object d)
{
Node temp = head;
while (temp != null)
{
if (temp.Data.Equals(d))
{
return temp;
}
temp = temp.Next;
}
return null;
}
但是,如果我替换
temp.Data.Equals(d)
与 temp.Data == d
即使temp.Data 和d 的值都为“3”,它也会停止工作。 == 不适用于对象类型变量的任何原因?
这是 Main 函数的 sn-p -
SinglyLinkedList list = new SinglyLinkedList();
list.Insert(1);
list.Insert(2);
list.Insert(3);
list.Insert(4);
list.Insert(5);
list.Print();
Node mid = list.Search(3);
我相信,由于我传递了一个 int 值 3 并且 Search 方法需要一个对象类型,因此它会成功地将 3 装箱为对象类型。但是,不知道为什么 == 不起作用,而 .Equals 起作用。
== 运算符是否仅针对值类型重载?
【问题讨论】:
-
你应该使用泛型。
-
是的,这只是为了练习目的。我意识到泛型已经有一个 LinkedList 实现
标签: c# equality singly-linked-list equals-operator