2012-11-24 160 views
2

我有我自己的類MyTreeNodeTreeNode得出:如何覆蓋TreeNode.Clone()方法?

public class MyTreeNode : System.Windows.Forms.TreeNode 
{ 
    [Localizable(true)] 
    public bool Foo { get; set; } 
} 

我嘗試克隆節點:

MyTreeNode myTreeNode = new MyTreeNode(); 
myTreeNode.Foo = foo; 
// 
//And here is the problem, all fields have been copied to the new node but Foo 
// 
MyTreeNode newNode = (MyTreeNode)myTreeNode.Clone(); 

在結果,newNode有空Foo場。我怎樣才能解決這個問題 ?

回答

3

如果你想Foo被複制以及調用Clone()時,你需要重寫Clone()方法並添加邏輯這樣做。

所有你需要做的就是添加到您的MyTreeNode類:

public override object Clone() 
{ 
    var obj = (MyTreeNode)base.Clone(); 
    obj.Foo = this.Foo; 
    return obj; 
} 
1

嘗試這樣的事情在你的MyTreeNode類

public override object Clone() 
{ 
    object objReturn = base.Clone(); 
    ((MyTreeNode)objReturn).Foo = this.Foo; 
    return objReturn; 
}