创建对象的副本(在继承上)

时间:2016-06-14 19:49:28

标签: c#

我有一个创建对象副本的方法

for (let [index, value] of Array.from(document.querySelectorAll('div')).entries()) {
    console.log(index); // Key
    console.log(value); // Value
}

还有一些像这样的儿童班:

protected Node CreateCopy()
{
    return new Node(InputCount, OutpuCount, Name);;
}

有没有办法自动创建它们的副本?

(需要儿童类的类型不是基础)

2 个答案:

答案 0 :(得分:4)

  

有没有办法自动创建它们的副本?

您可以使用从Object继承的MemberwiseClone方法:

protected Node CreateCopy()
{
    return (Node)MemberwiseClone();
}

请注意,它将是浅层副本,即引用类型成员将通过引用复制,而不是克隆。

如果需要深层复制,可以序列化和反序列化对象(效率不高非常低效,仅适用于可序列化类型),或使用AutoMapper之类的工具。

答案 1 :(得分:1)

如果您需要基类的副本,Thomas Levesque的答案很棒。但是既然你要求孩子类型,我只会添加这个经典的OOP建议:

class Node 
{
    protected int _num;
    protected string _text;

    public Node(int num, string text)
    {
        _num = num;
        _text = text;
    }

    public virtual Node Clone()
    {
        return new Node(_num, _text);
    }
}

class SuperNode : Node
{
    DateTime _superTime;

    public SuperNode(int num, string text, DateTime time)  :base(num, text)
    {
        _superTime = time;
    }

    public override Node Clone()
    {
        return new SuperNode(_num, _text, _superTime);
    }
} 
相关问题