【问题标题】:c# object loses reference when removed from listc# 对象从列表中删除时丢失引用
【发布时间】:2011-05-21 22:46:54
【问题描述】:

我有一个非常奇怪的问题。基本上,我创建了一个名为 TreeNode 的类,它代表树中的一个节点。然后我通过将所有节点添加到列表来创建树。

class TreeNode
{

    private TreeNode parent, lChild, rChild;
    private int key, val;

    public int Key
    {
        get { return key; }
        set { key = value; }
    }
    public int Val
    {
        get { return val; }
        set { val = value; }
    }

    public TreeNode Parent
    {
        get { return parent; }
        set { parent = value; }
    }
    public TreeNode LChild
    {
        get { return lChild; }
    }
    public TreeNode RChild
    {
        get { return rChild; }
    }

    public TreeNode(int k, int v)
    {
        key = k;
        val = v;
    }

    public void SetChild(TreeNode leftChild, TreeNode rightChild)
    {
        this.lChild = leftChild;
        this.rChild = rightChild;

    }

    public bool isLeaf()
    {
        if (this.lChild == null && this.rChild == null) 
        {
            return true;
        } else 
        {
            return false;
        }
    }

    public bool isParent()
    {
        if (this.parent == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public void SetParent(TreeNode Parent)
    {
        this.parent = Parent;
    }
}

因此,如果我在创建树之后放置一个断点并将鼠标悬停在 Visual Studio 中的列表上,我可以看到树的结构 - 所有引用从根到叶都完美地工作。

如果我执行以下操作:

TreeNode test = newTree[newTree.Count - 1];

请注意:

private List<TreeNode> newTree = new List<TreeNode>();

它返回根节点 - 再次悬停我可以向下一级(即左孩子或右孩子),但这些孩子之后没有任何对他们孩子的引用。

我想知道由于测试节点不是列表的一部分,我是否丢失了对列表中其他节点的内存引用?

任何帮助将不胜感激。

谢谢 汤姆

【问题讨论】:

    标签: c# list reference tree


    【解决方案1】:

    好像我发现了问题 - 我没有正确更新某些父节点及其相关子节点 - 问题已解决。

    感谢您的帮助 汤姆

    【讨论】:

      【解决方案2】:

      你确定你没有(注意你的代码中 new 和 tree 之间没有空格)

      TreeNode test = new Tree[newTree.Count - 1]; 
      

      这将创建一个新的空树数组(可能不是您想要的),并使您的原始树无根且无法访问。

      你能确定你的代码是正确的吗?

      【讨论】:

      • 嗨,我很抱歉没有更清楚......'newtree' 是 TreeNode 的列表 - 我知道愚蠢的命名约定,我只是懒惰。所以代码是正确的,谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      相关资源
      最近更新 更多