C#中指向另一个引用元素的引用元素

Reference element pointing to another reference element in C#

我有以下节点和循环链表类:

class Node
    {
        public Node next;
        public int data;
        public Node(int data, Node node)
        {
            this.data = data;
            this.next = node;
        }
    }

class CircularLinkedList
    {
        private int cRLstLength = 0;
        private Node head, tail;
        // ... other functions on Circular Linked list
    }

我正在尝试类似的东西:

CircularLinkedList cRLst = new CircularLinkedList(); 
Node headPointer = cRLst.head;
Node refToHeadPointer = headPointer;
Console.WriteLine("The data here is {0}", refToHeadPointer.data);
headPointer = headPointer.next;
Console.WriteLine("The data value is now {0}", refToHeadPointer.data); 

我原以为最后一个控制台输出与之前的不同。事实证明,即使 headPointer 指向下一个元素,指向 headPointerrefToHeadPointer 仍然指向较旧的引用。这怎么可能? refToHeadPointer 指向 headPointer ,其值正在更改为 headPointer.nextrefToHeadPointer 保留较早的引用。我使用 C# 编写了这段代码。

我认为您误解了引用类型变量在 C# 中的工作方式。 Reference-type variables in C# store an address that points to an object in memory. 这听起来像指针,在某种程度上确实如此,但其行为与指针在其他语言中的行为方式不同。

这是您的代码中发生的事情:

CircularLinkedList cRLst = new CircularLinkedList(); 

//take the address stored cRLst.head and store it in the variable headPointer 
Node headPointer = cRLst.head;

//take the address stored in headPointer and store it in the variable refToHeadPointer
Node refToHeadPointer = headPointer;

//As of now, crLst.head, headPointer and refToHeadPointer all hold the same address
//Read: they "point" to the same object in memory
Console.WriteLine("The data here is {0}", refToHeadPointer.data);

//Take the address stored in headPointer.next and store it in the variable headPointer
headPointer = headPointer.next;

//As of now, headPointer and refToHeadPointer contain addresses to different objects
//refToHeadPointer is a completely separate variable from headPointer. 
//Changing the address in headPointer doesn't change the address in refToHeadPointer
//headPointer holds an address that points to the current node (headPointer.next)
//refToHeadPointer holds an address that points to the original node (cRLst.head)
Console.WriteLine("The data value is now {0}", refToHeadPointer.data);