14

我希望在 C# 中实现我的类层次结构的深拷贝

public Class ParentObj : ICloneable
{
    protected int   myA;
    public virtual Object Clone ()
        {
             ParentObj newObj = new ParentObj();
             newObj.myA = theObj.MyA;
             return newObj;
        }
}

public Class ChildObj : ParentObj
{
    protected int   myB;
    public override Object Clone ( )
        {
             Parent newObj = this.base.Clone();
             newObj.myB = theObj.MyB;

             return newObj;
        }
}

这将不起作用,因为当克隆孩子时只有一个父母是新的。在我的代码中,一些类有很大的层次结构。

推荐的方法是什么?在不调用基类的情况下克隆每个级别的所有内容似乎是错误的?这个问题必须有一些巧妙的解决方案,它们是什么?

我可以感谢大家的回答。看到一些方法真的很有趣。我认为如果有人给出一个完整的反思答案的例子会很好。+1 等待!

4

8 回答 8

32

典型的方法是使用 C++ 中的“复制构造函数”模式:

 class Base : ICloneable
 { 
     int x;

     protected Base(Base other)
     {
         x = other.x;
     }

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

 class Derived : Base
 { 
     int y;

     protected Derived(Derived other)
          : Base(other)
     {
         y = other.y;
     }

     public override object Clone()
     {
         return new Derived(this);
     }
 }

另一种方法是Object.MemberwiseClone在实现中使用Clone- 这将确保结果始终是正确的类型,并允许覆盖扩展:

 class Base : ICloneable
 { 
     List<int> xs;

     public virtual object Clone()
     {
         Base result = this.MemberwiseClone();

         // xs points to same List object here, but we want
         // a new List object with copy of data
         result.xs = new List<int>(xs);

         return result;
     }
 }

 class Derived : Base
 { 
     List<int> ys;

     public override object Clone()
     {
         // Cast is legal, because MemberwiseClone() will use the
         // actual type of the object to instantiate the copy.
         Derived result = (Derived)base.Clone();

         // ys points to same List object here, but we want
         // a new List object with copy of data
         result.ys = new List<int>(ys);

         return result;
     }
 }

这两种方法都要求层次结构中的所有类都遵循该模式。使用哪一个是一个偏好问题。

如果您只是有任何随机类实现ICloneable而不保证实现(除了遵循 的文档化语义ICloneable),则无法扩展它。

于 2009-10-15T16:40:55.230 回答
7

尝试序列化技巧:

public object Clone(object toClone)
{
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms= new MemoryStream();
    bf.Serialize(ms, toClone);
    ms.Flush();
    ms.Position = 0;
    return bf.Deserialize(ms);
}
于 2009-10-15T16:33:29.600 回答
7

警告:

应非常谨慎地使用此代码。使用风险自负。此示例按原样提供,不提供任何形式的保证。


还有另一种方法可以在对象图上执行深度克隆。在考虑使用此示例时,请务必注意以下事项:

缺点:

  1. 除非将这些引用提供给 Clone(object, ...) 方法,否则对外部类的任何引用也将被克隆。
  2. 不会在克隆对象上执行构造函数,它们会按原样复制。
  3. 不会执行任何 ISerializable 或序列化构造函数。
  4. 无法更改此方法在特定类型上的行为。
  5. 它会克隆所有内容,Stream、AppDomain、Form 等等,而这些可能会以可怕的方式破坏您的应用程序。
  6. 它可能会中断,而使用序列化方法更有可能继续工作。
  7. 下面的实现使用递归,如果您的对象图太深,很容易导致堆栈溢出。

那么你为什么要使用它呢?

优点:

  1. 它对所有实例数据进行完整的深度复制,而无需在对象中进行编码。
  2. 它保留重构对象中的所有对象图引用(甚至是循环的)。
  3. 它的执行速度比二进制格式化程序高 20 倍以上,而且内存消耗更少。
  4. 它不需要任何东西,不需要属性、实现的接口、公共属性,什么都不需要。

代码用法:

你只需用一个对象调用它:

Class1 copy = Clone(myClass1);

或者假设您有一个子对象并且您订阅了它的事件......现在您想要克隆该子对象。通过提供克隆的对象列表,您可以保留对象图的某些部分:

Class1 copy = Clone(myClass1, this);

执行:

现在让我们先把简单的东西弄清楚……这是入口点:

public static T Clone<T>(T input, params object[] stableReferences)
{
    Dictionary<object, object> graph = new Dictionary<object, object>(new ReferenceComparer());
    foreach (object o in stableReferences)
        graph.Add(o, o);
    return InternalClone(input, graph);
}

现在这很简单,它只是在克隆期间为对象构建一个字典映射,并用任何不应克隆的对象填充它。您会注意到提供给字典的比较器是一个 ReferenceComparer,让我们看看它的作用:

class ReferenceComparer : IEqualityComparer<object>
{
    bool IEqualityComparer<object>.Equals(object x, object y)
    { return Object.ReferenceEquals(x, y); }
    int IEqualityComparer<object>.GetHashCode(object obj)
    { return RuntimeHelpers.GetHashCode(obj); }
}

这很容易,只是一个强制使用 System.Object 的 get hash 和 reference 相等性的比较器......现在是艰苦的工作:

private static T InternalClone<T>(T input, Dictionary<object, object> graph)
{
    if (input == null || input is string || input.GetType().IsPrimitive)
        return input;

    Type inputType = input.GetType();

    object exists;
    if (graph.TryGetValue(input, out exists))
        return (T)exists;

    if (input is Array)
    {
        Array arItems = (Array)((Array)(object)input).Clone();
        graph.Add(input, arItems);

        for (long ix = 0; ix < arItems.LongLength; ix++)
            arItems.SetValue(InternalClone(arItems.GetValue(ix), graph), ix);
        return (T)(object)arItems;
    }
    else if (input is Delegate)
    {
        Delegate original = (Delegate)(object)input;
        Delegate result = null;
        foreach (Delegate fn in original.GetInvocationList())
        {
            Delegate fnNew;
            if (graph.TryGetValue(fn, out exists))
                fnNew = (Delegate)exists;
            else
            {
                fnNew = Delegate.CreateDelegate(input.GetType(), InternalClone(original.Target, graph), original.Method, true);
                graph.Add(fn, fnNew);
            }
            result = Delegate.Combine(result, fnNew);
        }
        graph.Add(input, result);
        return (T)(object)result;
    }
    else
    {
        Object output = FormatterServices.GetUninitializedObject(inputType);
        if (!inputType.IsValueType)
            graph.Add(input, output);
        MemberInfo[] fields = inputType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        object[] values = FormatterServices.GetObjectData(input, fields);

        for (int i = 0; i < values.Length; i++)
            values[i] = InternalClone(values[i], graph);

        FormatterServices.PopulateObjectMembers(output, fields, values);
        return (T)output;
    }
}

您会立即注意到数组和委托副本的特殊情况。每个都有自己的原因,首先 Array 没有可以克隆的“成员”,因此您必须处理此问题并依赖浅层 Clone() 成员,然后克隆每个元素。至于委托,它可以在没有特殊情况的情况下工作;但是,这会更安全,因为它不会复制 RuntimeMethodHandle 之类的东西。如果您打算在核心运行时的层次结构中包含其他内容(例如 System.Type),我建议您以类似的方式显式处理它们。

最后一种情况,也是最常见的,就是使用与 BinaryFormatter大致相同的例程。这些允许我们从原始对象中弹出所有实例字段(公共或私有),克隆它们,并将它们粘贴到一个空对象中。这里的好处是 GetUninitializedObject 返回一个尚未在其上运行 ctor 的新实例,这可能会导致问题并降低性能。

以上是否有效将在很大程度上取决于您的特定对象图和其中的数据。如果您控制图中的对象并且知道它们没有引用像线程这样的愚蠢事物,那么上面的代码应该可以很好地工作。

测试:

这是我最初为测试而写的:

class Test
{
    public Test(string name, params Test[] children)
    {
        Print = (Action<StringBuilder>)Delegate.Combine(
            new Action<StringBuilder>(delegate(StringBuilder sb) { sb.AppendLine(this.Name); }),
            new Action<StringBuilder>(delegate(StringBuilder sb) { sb.AppendLine(this.Name); })
        );
        Name = name;
        Children = children;
    }
    public string Name;
    public Test[] Children;
    public Action<StringBuilder> Print;
}

static void Main(string[] args)
{
    Dictionary<string, Test> data2, data = new Dictionary<string, Test>(StringComparer.OrdinalIgnoreCase);

    Test a, b, c;
    data.Add("a", a = new Test("a", new Test("a.a")));
    a.Children[0].Children = new Test[] { a };
    data.Add("b", b = new Test("b", a));
    data.Add("c", c = new Test("c"));

    data2 = Clone(data);
    Assert.IsFalse(Object.ReferenceEquals(data, data2));
    //basic contents test & comparer
    Assert.IsTrue(data2.ContainsKey("a"));
    Assert.IsTrue(data2.ContainsKey("A"));
    Assert.IsTrue(data2.ContainsKey("B"));
    //nodes are different between data and data2
    Assert.IsFalse(Object.ReferenceEquals(data["a"], data2["a"]));
    Assert.IsFalse(Object.ReferenceEquals(data["a"].Children[0], data2["a"].Children[0]));
    Assert.IsFalse(Object.ReferenceEquals(data["B"], data2["B"]));
    Assert.IsFalse(Object.ReferenceEquals(data["B"].Children[0], data2["B"].Children[0]));
    Assert.IsFalse(Object.ReferenceEquals(data["B"].Children[0], data2["A"]));
    //graph intra-references still in tact?
    Assert.IsTrue(Object.ReferenceEquals(data["B"].Children[0], data["A"]));
    Assert.IsTrue(Object.ReferenceEquals(data2["B"].Children[0], data2["A"]));
    Assert.IsTrue(Object.ReferenceEquals(data["A"].Children[0].Children[0], data["A"]));
    Assert.IsTrue(Object.ReferenceEquals(data2["A"].Children[0].Children[0], data2["A"]));
    data2["A"].Name = "anew";
    StringBuilder sb = new StringBuilder();
    data2["A"].Print(sb);
    Assert.AreEqual("anew\r\nanew\r\n", sb.ToString());
}

最后注:

老实说,这在当时是一个有趣的练习。在数据模型上进行深度克隆通常是一件好事。今天的现实是,大多数数据模型都是生成的,它们通过生成的深度克隆例程淘汰了上述黑客的有用性。我强烈建议生成您的数据模型,它能够执行深度克隆,而不是使用上面的代码。

于 2009-10-15T23:31:25.453 回答
2

最好的方法是序列化你的对象,然后返回反序列化的副本。它将获取有关您的对象的所有内容,除了那些标记为不可序列化的对象,并使继承序列化变得容易。

[Serializable]
public class ParentObj: ICloneable
{
    private int myA;
    [NonSerialized]
    private object somethingInternal;

    public virtual object Clone()
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(ms, this);
        object clone = formatter.Deserialize(ms);
        return clone;
    }
}

[Serializable]
public class ChildObj: ParentObj
{
    private int myB;

    // No need to override clone, as it will still serialize the current object, including the new myB field
}

这不是最有效的事情,但也不是替代方案:重新选举。此选项的好处是它可以无缝继承。

于 2009-10-15T16:36:09.123 回答
0
  1. 您可以使用反射来循环所有变量并复制它们。(慢)如果它对您的软件来说很慢,您可以使用 DynamicMethod 并生成 il。
  2. 序列化对象并再次反序列化。
于 2009-10-15T16:24:18.837 回答
0

我认为您在这里没有正确实施 ICloneable ;它需要一个没有参数的 Clone() 方法。我推荐的是这样的:

public class ParentObj : ICloneable
{
    public virtual Object Clone()
    {
        var obj = new ParentObj();

        CopyObject(this, obj);
    }

    protected virtual CopyObject(ParentObj source, ParentObj dest)
    {
        dest.myA = source.myA;
    }
}

public class ChildObj : ParentObj
{
    public override Object Clone()
    {
        var obj = new ChildObj();
        CopyObject(this, obj);
    }

    public override CopyObject(ChildObj source, ParentObj dest)
    {
        base.CopyObject(source, dest)
        dest.myB = source.myB;
    }
}

请注意,CopyObject() 基本上是 Object.MemberwiseClone(),可能您要做的不仅仅是复制值,您还将克隆任何属于类的成员。

于 2009-10-15T16:32:28.227 回答
0

尝试使用以下[使用关键字“new”]

public class Parent
{
  private int _X;
  public int X{ set{_X=value;} get{return _X;}}
  public Parent copy()
  {
     return new Parent{X=this.X};
  }
}
public class Child:Parent
{
  private int _Y;
  public int Y{ set{_Y=value;} get{return _Y;}}
  public new Child copy()
  {
     return new Child{X=this.X,Y=this.Y};
  }
}
于 2010-06-11T17:51:23.473 回答
-1

您应该改用该MemberwiseClone方法:

public class ParentObj : ICloneable
{
    protected int myA;
    public virtual Object Clone()
    {
        ParentObj newObj = this.MemberwiseClone() as ParentObj;
        newObj.myA = this.MyA; // not required, as value type (int) is automatically already duplicated.
        return newObj;
    }
}

public class ChildObj : ParentObj
{
    protected int myB;
    public override Object Clone()
        {
             ChildObj newObj = base.Clone() as ChildObj;
             newObj.myB = this.MyB; // not required, as value type (int) is automatically already duplicated

             return newObj;
        }
}
于 2009-10-15T16:50:54.433 回答