2010-12-08 71 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

好像我找到了問題 - 我沒有正確更新一些父節點及其相關的子節點 - 問題已解決。

感謝您的幫助 湯姆