从基类方法克隆派生类 [英] Clone derived class from base class method

查看:92
本文介绍了从基类方法克隆派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象的基类Base,它具有一些共同的属性,许多派生的基类实现了不同的逻辑,但很少有其他字段.

I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields.

public abstract Base
{
    protected int field1;
    protected int field2;
    ....

    protected Base() { ... }
}

有时我需要克隆派生类.所以我的猜测是,只需在基类中创建一个虚拟的Clone方法,并仅在具有其他字段的派生类中覆盖它,但是当然我的Base类将不再是抽象的(这不是问题)因为它只有一个protected构造函数).

Sometimes I need to clone the derived class. So my guess was, just make a virtual Clone method in my base class and only override it in derived classes that have additional fields, but of course my Base class wouldn't be abstract anymore (which isn't a problem since it only has a protected constructor).

public Base
{
    protected int field1;
    protected int field2;
    ....

    protected Base() { ... }

    public virtual Base Clone() { return new Base(); }
}

public A : Base { }
public B : Base { }

  1. 问题是,由于我在基类中不知道派生类的类型,即使我在派生类上调用它,也不会导致它具有Base类实例吗? (a.Clone();)(实际上是在测试之后,但是我的测试设计得不好,这就是为什么我对此有所怀疑的原因)

  1. The thing is, since I can't know the type of the derived class in my Base one, wouldn't this lead to have a Base class instance even if I call it on the derived ones ? (a.Clone();) (actually after a test this is what is happening but perhaps my test wasn't well designed that's why I have a doubt about it)

是否有一种好的方法(模式)来实现基本的Clone方法,该方法可以按我的预期工作,或者我必须在每个派生类中编写相同的代码(我真的想避免那...)

Is there a good way (pattern) to implement a base Clone method that would work as I expect it or do I have to write the same code in every derived class (I'd really like to avoid that...)

感谢您的帮助

推荐答案

只需覆盖Clone并使用另一种方法CreateInstance然后执行操作即可.

Just override the Clone and have another method to CreateInstance then do your stuff.

这样,您只有Base类可以避免泛型.

This way you could have only Base class avoiding generics.

public Base
{
    protected int field1;
    protected int field2;
    ....

    protected Base() { ... }

    public virtual Base Clone() 
    { 
        var bc = CreateInstanceForClone();
        bc.field1 = 1;
        bc.field2 = 2;
        return bc;
    }

    protected virtual Base CreateInstanceForClone()
    {
        return new Base(); 
    }
}


public A : Base 
{     
    protected int fieldInA;
    public override Base Clone() 
    { 
        var a = (A)base.Clone();
        a.fieldInA =5;
        return a;
    }

    protected override Base CreateInstanceForClone()
    {
        return new A(); 
    }
}

这篇关于从基类方法克隆派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆