2010-12-08 70 views
0

我有一个很奇怪的问题。基本上我创建了一个名为TreeNode的类,它表示树中的一个节点。然后通过将所有节点添加到List来创建树。c#对象从列表中删除时丢失参考

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

返回根节点 - 然后再次将鼠标悬停在我可以做下来一个水平(即左子或右孩子),但这些孩子之后没有任何关于他们的孩子的参考。

我想知道如果由于测试节点不是列表中的一部分而导致内存中的引用丢失到列表中的其他节点?

任何帮助将不胜感激。

感谢 汤姆

回答

1

你确定你没有(请注意,在你的代码的新树之间没有空格)

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

这将树创建一个新的空数组(可能不是什么你的意图),并保持你的原始树木根深蒂固,无法进入。

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

+0

这也是我的猜测。 – 2010-12-08 00:25:14

0

好像我找到了问题 - 我没有正确更新一些父节点及其相关的子节点 - 问题已解决。

感谢您的帮助 汤姆