C# 对对象副本所做的更改将反映在原始对象中
在下面的代码片段中,我对“current”对象进行了更改,它是“head”对象的副本。但是,更改会反映到全局头部对象C# 对对象副本所做的更改将反映在原始对象中,c#,C#,在下面的代码片段中,我对“current”对象进行了更改,它是“head”对象的副本。但是,更改会反映到全局头部对象 class Node { public Node next; //pointer public Object data; //data public Node(Object d) { data = d; } } public class Custom
class Node
{
public Node next; //pointer
public Object data; //data
public Node(Object d)
{
data = d;
}
}
public class CustomLinkedList
{
private Node head = new Node(null); //head of linked list
public void Add(Object data)
{
Node newNode = new Node(data);
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = newNode;
}
}
原因是-类是引用类型 引用类型是一种类型,其值是对适当数据的引用,而不是数据本身。这就是为什么更改一个对象也会更改另一个对象 阅读这些- 解决方案是深度克隆考虑中的对象 请阅读以下内容-