指向 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.nextrefToHeadPointer保留较早引用headPointer。我使用 C# 编写此代码。

我认为您误解了引用类型变量在 C# 中的工作方式。C# 中的引用类型变量存储指向内存中对象的地址。这听起来像一个指针,在某种程度上确实如此,但该行为与其他语言中的指针行为不同。

下面是代码中发生的情况:

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

最新更新