4

Coming from a C++ background, I am finding cloning of objects in C# a little hard to get used to. To clear up some of my confusion, I am looking for an elegant way to clone an object of a base type to a derived type.

To illustrate:

public class Base
{
    public string Member1;
    public int Member2;
    public float Member3;
    public bool Member4;
}

public class Derived : Base
{
    public List<Base> Children;
}

Base base = new Base();

And with that I want to create an instance of "Derived" whilst doing a memberwise copy of the Base object - preferably without assigning them manually.

Note: Maybe this would be more suited to a value type?

4

2 回答 2

4

由于您无法更改对象的类型,因此您有几个选择:

  • 封装 Base
  • 使用复制值的构造函数Base
  • Base通过反射或类似方法复制属性

对于后者,MiscUtil有一个有用的工具:

Base b= ...
Derived item = PropertyCopy<Derived>.CopyFrom(b);

对于封装:

public class Derived
{
    readonly Base b;
    public Derived(Base b) {this.b=b;}
    public List<Base> Children;
    public string Member1 {get {return b.Member1;} set {...} }
    public int Member2 {etc}
    public float Member3 {etc}
    public bool Member4 {etc}
}

或作为手动副本:

public class Derived : Base
{
    public Derived(Base b) {
        this.Member1 = b.Member1;
        // etc
    }
    // additional members...
}

或(评论)让基地复制自己:

public class Derived : Base
{
    public Derived(Base b) : base(b) { }
    // additional members...
}
public class Base
{
    // members not shown...
    public Base() {}
    protected Base(Base b) {
       this.Member1 = b.Member1;
        // etc
    }
    // additional members...
}

(其中Base的构造函数从 初始化字段Base

于 2009-08-26T13:35:37.597 回答
2
/// Clone all fields from an instance of base class TSrc into derived class TDst
public static TDst Clone<TSrc, TDst>(TSrc source, TDst target)
    where TDst : TSrc
{
    var bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
    foreach (FieldInfo fis in source.GetType().GetFields(bf))
        fis.SetValue(target, fis.GetValue(source));
    return target;
}

/// Create a new instance of a derived class, cloning all fields from type TSrc
public static TDst Clone<TSrc, TDst>(TSrc source)
    where TDst : TSrc, new()
{
    return Clone(source, new TDst());
}
于 2011-11-06T20:53:28.803 回答