【问题标题】:C# Clone a specialized TreeNode containing another Object of type ObjectC# 克隆一个包含另一个 Object 类型的 Object 的专用 TreeNode
【发布时间】:2015-09-25 20:47:53
【问题描述】:

我一直在寻找一种简单的解决方案来克隆包含其他对象的对象。

public class TPFTestCaseTreeNode: TreeNode, ICloneable
{
    public Object Obj;

    public TPFTestCaseTreeNode(string Title, Object O)
    {
        // Set attributes for the TreeNode
        Text = Title; // not sure which one we need
        Name = Title; // not sure which one we need

        // And additionally, remember the test case object
        Obj = O;
    }
} 

对于克隆,我正在使用:

foreach(TreeNode t in listAllTestCases)
{
    if(t.Name.Equals(testCaseIdDesc))
    {
        theNode = (TreeNode)((ICloneable)t).DeepClone();                     
    }
}

listAllTestCases 包含所有类型为“TPFTestCaseTreeNode”的树节点。

“t”在循环中,根据调试器模式确实包含“Obj”的有效值

我也尝试过普通的 Clone() 和 DeepClone(),它们都无法克隆对象“Obj”的状态。它在克隆对象树节点“theNode”中始终保持为空。

谁能提供一个合理的解释为什么包含另一个对象的对象的克隆在这里失败? 这是克隆前和克隆后的两种状态。 Initial State Cloned Object

请注意,我什至也尝试过 binaryformatter(序列化/反序列化机制)。但是,对象“Obj”仍然为空。

【问题讨论】:

标签: c# treeview clone icloneable


【解决方案1】:

所以最后,我不得不使用 Treenode“Tag”属性本身并将我的“Obj”分配给它。 但是,这里的 DeepClone() 或 Clone() 也没有克隆此标记属性值。

基本上我必须循环实际对象的每个属性并构建克隆的对象。

自定义类型的 Treenode 很麻烦,但现在可以正常工作了。

感谢大家的宝贵意见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    相关资源
    最近更新 更多