理解c#递归编程中的类行为

  • 本文关键字:递归 编程 理解 c#
  • 更新时间 :
  • 英文 :


ListGenerator接受int类型的数组,并将其转换为递归对象。

public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public static ListNode GenerateList(int[] nums)
{
if (nums == null || nums.Length == 0) { return null; }
var i = 0;
var first = new ListNode(nums[i]);
var current = first;
while (++i < nums.Length)
{
current.next = new ListNode(nums[i]);
current = current.next;
}
return first;
}

我知道c#中的类是引用类型,所以在执行这行代码current.next = new ListNode(nums[i]);之后,first变量的值将与current相同,一切都很好。

current = current.next;之后firstcurrent的值不相同。实际上,next属性在first中有一个值,但在current中为空。我不明白为什么会这样。在我看来,first必须与current相同,但它不是。

对于var current = first;,您将first中的引用复制到current。在这一点上,它们指的是同一个对象。current.next中的任何变化都可以在first.next中看到。

之后你重新赋值current,所以现在它指向first以外的东西。first中的引用不受影响。

最新更新