【问题标题】:Understanding C# class behavior in recursive programming了解递归编程中的 C# 类行为
【发布时间】:2022-06-16 16:59:49
【问题描述】:

有一个 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;之后first和current的值不一样。实际上,next 属性在first 中有一个值,但在current 中为空。 我不明白为什么会这样。在我看来,first 必须与current 相同,但事实并非如此。

【问题讨论】:

  • 为什么你会首先想到改变? first 永远不会被重新分配。

标签: c#


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 2017-03-17
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
相关资源
最近更新 更多