Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对对象副本所做的更改将反映在原始对象中_C# - Fatal编程技术网

C# 对对象副本所做的更改将反映在原始对象中

C# 对对象副本所做的更改将反映在原始对象中,c#,C#,在下面的代码片段中,我对“current”对象进行了更改,它是“head”对象的副本。但是,更改会反映到全局头部对象 class Node { public Node next; //pointer public Object data; //data public Node(Object d) { data = d; } } public class Custom

在下面的代码片段中,我对“current”对象进行了更改,它是“head”对象的副本。但是,更改会反映到全局头部对象

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;
            }
    }

原因是-类是引用类型

引用类型是一种类型,其值是对适当数据的引用,而不是数据本身。这就是为什么更改一个对象也会更改另一个对象

阅读这些-

解决方案是深度克隆考虑中的对象

请阅读以下内容-