实现 ICloneable 的正确方法

在类层次结构中实现 ICloneable的正确方法是什么?假设我有一个抽象类 DrawingObject。另一个抽象类 RectangularObject继承自 DrawingObject。然后还有多个具体的类,如 ShapeTextCircle等,它们都是从 RectangularObject继承而来的。我想在 DrawingObject上实现 ICloneable,然后将它沿着层次结构进行下去,在每个级别复制可用的属性,并在下一个级别调用父级的 DrawingObject0。

但问题是,由于前两个类是抽象的,我无法在 Clone()方法中创建它们的对象。因此,我必须在每个具体类中复制属性复制过程。还是有更好的办法?

114323 次浏览

在我看来,最明确的方法是在 MemoryStream中应用 BinaryFormatter的二进制序列化。

关于 C # 中深度克隆的 MSDN 线程中建议使用上述方法。

为基类提供一个受保护且可重写的 CreateClone()方法,该方法创建当前类的新(空)实例。然后让基类的 Clone()方法调用该方法以多态方式实例化一个新实例,然后基类可以将其字段值复制到该实例。

派生的非抽象类可以重写 CreateClone()方法来实例化适当的类,而引入新字段的所有派生类都可以重写 Clone(),以便在调用继承版本的 Clone()之后将其附加字段值复制到新实例中。

public CloneableBase : ICloneable
{
protected abstract CloneableBase CreateClone();


public virtual object Clone()
{
CloneableBase clone = CreateClone();
clone.MyFirstProperty = this.MyFirstProperty;
return clone;
}


public int MyFirstProperty { get; set; }
}


public class CloneableChild : CloneableBase
{
protected override CloneableBase CreateClone()
{
return new CloneableChild();
}


public override object Clone()
{
CloneableChild clone = (CloneableChild)base.Clone();
clone.MySecondProperty = this.MySecondProperty;
return clone;
}


public int MySecondProperty { get; set; }
}

如果你想跳过第一个重写步骤(至少在默认情况下) ,你也可以假设一个缺省构造函数签名(例如无参数) ,并尝试使用带反射的构造函数签名来实例化一个克隆实例。像这样,只有构造函数与默认签名不匹配的类才必须重写 CreateClone()

默认 CreateClone()实现的一个非常简单的版本可能如下所示:

protected virtual CloneableBase CreateClone()
{
return (CloneableBase)Activator.CreateInstance(GetType());
}

这是我几年前写的一些样本代码的复制粘贴。

这些天,我避免使用需要克隆支持的设计; 我发现大多数此类设计都有些古怪。相反,我大量使用不可变类,以避免首先需要克隆。

话虽如此,下面是克隆模式的样本:

using System;
using System.IO;
using System.Diagnostics;


/*


This code demonstrates a cloning pattern that you can use for class hierarchies.


The abstract base class specifies an abstract Clone() method which must be implemented by all derived classes.
Every class except the abstract base class must have a protected copy constructor.


This protected copy constructor will:


(1) call the base class' copy constructor, and
(2) set any new fields introduced in the derived class.


This code also demonstrates an implementation of Equals() and CopyFrom().


*/


namespace CloningPattern
{
//—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————


static class Program
{
static void Main()
{
Derived2 test = new Derived2()
{
IntValue = 1,
StringValue = "s",
DoubleValue = 2,
ShortValue = 3
};


Derived2 copy = Clone(test);
Console.WriteLine(copy);
}


static Derived2 Clone(AbstractBase item)
{
AbstractBase abstractBase = (AbstractBase) item.Clone();
Derived2 result = abstractBase as Derived2;
Debug.Assert(result != null);
return result;
}
}


//—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————


public abstract class AbstractBase: ICloneable
{
// Sample data field.


public int IntValue { get; set; }


// Canonical way of providing a Clone() operation
// (except that this is abstract rather than virtual, since this class
// is itself abstract).


public abstract object Clone();


// Default constructor.


protected AbstractBase(){}


// Copy constructor.


protected AbstractBase(AbstractBase other)
{
if (other == null)
{
throw new ArgumentNullException("other");
}


this.copyFrom(other);
}


// Copy from another instance over the top of an already existing instance.


public virtual void CopyFrom(AbstractBase other)
{
if (other == null)
{
throw new ArgumentNullException("other");
}


this.copyFrom(other);
}


// Equality check.


public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}


if (object.ReferenceEquals(this, obj))
{
return true;
}


if (this.GetType() != obj.GetType())
{
return false;
}


AbstractBase other = (AbstractBase)obj;


return (this.IntValue == other.IntValue);
}


// Get hash code.


public override int GetHashCode()
{
return this.IntValue.GetHashCode();
}


// ToString() for debug purposes.


public override string ToString()
{
return "IntValue = " + IntValue;
}


// Implement copying fields in a private non-virtual method, called from more than one place.


private void copyFrom(AbstractBase other)  // 'other' cannot be null, so no check for nullness is made.
{
this.IntValue = other.IntValue;
}
}


//—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————


public abstract class AbstractDerived: AbstractBase
{
// Sample data field.


public short ShortValue{ get; set; }


// Default constructor.


protected AbstractDerived(){}


// Copy constructor.


protected AbstractDerived(AbstractDerived other): base(other)
{
this.copyFrom(other);
}


// Copy from another instance over the top of an already existing instance.


public override void CopyFrom(AbstractBase other)
{
base.CopyFrom(other);
this.copyFrom(other as AbstractDerived);
}


// Comparison.


public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
{
return true;
}


if (!base.Equals(obj))
{
return false;
}


AbstractDerived other = (AbstractDerived)obj;  // This must succeed because if the types are different, base.Equals() returns false.


return (this.IntValue == other.IntValue);
}


// Get hash code.


public override int GetHashCode()
{
// "Standard" way of combining hash codes from subfields.


int hash = 17;


hash = hash * 23 + base.GetHashCode();
hash = hash * 23 + this.ShortValue.GetHashCode();


return hash;
}


// ToString() for debug purposes.


public override string ToString()
{
return base.ToString() + ", ShortValue = " + ShortValue;
}


// This abstract class doesn't need to implement Clone() because no instances of it
// can ever be created, on account of it being abstract and all that.
// If you COULD, it would look like this (but you can't so this won't compile):


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


// Implement copying fields in a private non-virtual method, called from more than one place.


private void copyFrom(AbstractDerived other)  // Other could be null, so check for nullness.
{
if (other != null)
{
this.ShortValue = other.ShortValue;
}
}
}


//—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————


public class Derived1: AbstractDerived
{
// Must declare a default constructor.


public Derived1(){}


// Sample data field.


public string StringValue{ get; set; }


// Implement Clone() by simply using this class' copy constructor.


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


// Copy from another instance over the top of an already existing instance.


public override void CopyFrom(AbstractBase other)
{
base.CopyFrom(other);
this.copyFrom(other as Derived1);
}


// Equality check.


public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
{
return true;
}


if (!base.Equals(obj))
{
return false;
}


Derived1 other = (Derived1)obj;  // This must succeed because if the types are different, base.Equals() returns false.


return (this.StringValue == other.StringValue);
}


// Get hash code.


public override int GetHashCode()
{
// "Standard" way of combining hash codes from subfields.


int hash = 17;


hash = hash * 23 + base.GetHashCode();
hash = hash * 23 + this.StringValue.GetHashCode();


return hash;
}


// ToString() for debug purposes.


public override string ToString()
{
return base.ToString() + ", StringValue = " + StringValue;
}


// Protected copy constructor. Used to implement Clone().
// Also called by a derived class' copy constructor.


protected Derived1(Derived1 other): base(other)
{
this.copyFrom(other);
}


// Implement copying fields in a private non-virtual method, called from more than one place.


private void copyFrom(Derived1 other)  // Other could be null, so check for nullness.
{
if (other != null)
{
this.StringValue = other.StringValue;
}
}
}


//—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————


public class Derived2: Derived1
{
// Must declare a default constructor.


public Derived2(){}


// Sample data field.


public double DoubleValue{ get; set; }


// Implement Clone() by simply using this class' copy constructor.


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


// Copy from another instance over the top of an already existing instance.


public override void CopyFrom(AbstractBase other)
{
base.CopyFrom(other);
this.copyFrom(other as Derived2);
}


// Equality check.


public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
{
return true;
}


if (!base.Equals(obj))
{
return false;
}


Derived2 other = (Derived2)obj;  // This must succeed because if the types are different, base.Equals() returns false.


return (this.DoubleValue == other.DoubleValue);
}


// Get hash code.


public override int GetHashCode()
{
// "Standard" way of combining hash codes from subfields.


int hash = 17;


hash = hash * 23 + base.GetHashCode();
hash = hash * 23 + this.DoubleValue.GetHashCode();


return hash;
}


// ToString() for debug purposes.


public override string ToString()
{
return base.ToString() + ", DoubleValue = " + DoubleValue;
}


// Protected copy constructor. Used to implement Clone().
// Also called by a derived class' copy constructor.


protected Derived2(Derived2 other): base(other)
{
// Canonical implementation: use ":base(other)" to copy all
// the base fields (which recursively applies all the way to the ultimate base)
// and then explicitly copy any of this class' fields here:


this.copyFrom(other);
}


// Implement copying fields in a private non-virtual method, called from more than one place.


private void copyFrom(Derived2 other)  // Other could be null, so check for nullness.
{
if (other != null)
{
this.DoubleValue = other.DoubleValue;
}
}
}
}

你可以很容易地用 object的保护方法 MemberwiseClone创建一个表面的克隆。

例如:

   public abstract class AbstractCloneable : ICloneable
{
public object Clone()
{
return this.MemberwiseClone();
}
}

如果您不需要任何类似深度副本的东西,那么您就不必在子类中执行任何操作。

MemberwiseClone 方法通过创建新对象创建浅表复制,然后将当前对象的非静态字段复制到新对象。如果字段是值类型,则执行该字段的逐位副本。如果字段是引用类型,则复制引用,但不复制引用对象; 因此,原始对象及其克隆引用同一对象。

如果在克隆逻辑中需要更多的智能,可以添加一个虚拟方法来处理引用:

   public abstract class AbstractCloneable : ICloneable
{
public object Clone()
{
var clone = (AbstractCloneable) this.MemberwiseClone();
HandleCloned(clone);
return clone;
}


protected virtual void HandleCloned(AbstractCloneable clone)
{
//Nothing particular in the base class, but maybe useful for children.
//Not abstract so children may not implement this if they don't need to.
}
}




public class ConcreteCloneable : AbstractCloneable
{
protected override void HandleCloned(AbstractCloneable clone)
{
//Get whathever magic a base class could have implemented.
base.HandleCloned(clone);


//Clone is of the current type.
ConcreteCloneable obj = (ConcreteCloneable) clone;


//Here you have a superficial copy of "this". You can do whathever
//specific task you need to do.
//e.g.:
obj.SomeReferencedProperty = this.SomeReferencedProperty.Clone();
}
}

至少您只允许具体类处理克隆,而抽象类具有 protected复制构造函数。在此基础上,你可以获取一个 DrawingObject的变量,然后像这样克隆它:

class Program
{
static void Main(string[] args)
{
DrawingObject obj1=new Circle(Color.Black, 10);
DrawingObject obj2=obj1.Clone();
}
}

您可能会认为这是一种欺骗,但我会使用扩展方法和反射:

public abstract class DrawingObject
{
public abstract void Draw();
public Color Color { get; set; }
protected DrawingObject(DrawingObject other)
{
this.Color=other.Color;
}
protected DrawingObject(Color color) { this.Color=color; }
}


public abstract class RectangularObject : DrawingObject
{
public int Width { get; set; }
public int Height { get; set; }
protected RectangularObject(RectangularObject other)
: base(other)
{
Height=other.Height;
Width=other.Width;
}
protected RectangularObject(Color color, int width, int height)
: base(color)
{
this.Width=width;
this.Height=height;
}
}


public class Circle : RectangularObject, ICloneable
{
public int Diameter { get; set; }
public override void Draw()
{
}
public Circle(Circle other)
: base(other)
{
this.Diameter=other.Diameter;
}
public Circle(Color color, int diameter)
: base(color, diameter, diameter)
{
Diameter=diameter;
}


#region ICloneable Members
public Circle Clone() { return new Circle(this); }
object ICloneable.Clone()
{
return Clone();
}
#endregion


}


public class Square : RectangularObject, ICloneable
{
public int Side { get; set; }
public override void Draw()
{
}
public Square(Square other)
: base(other)
{
this.Side=other.Side;
}
public Square(Color color, int side)
: base(color, side, side)
{
this.Side=side;
}


#region ICloneable Members
public Square Clone() { return new Square(this); }
object ICloneable.Clone()
{
return Clone();
}
#endregion


}


public static class Factory
{
public static T Clone<T>(this T other) where T : DrawingObject
{
Type t = other.GetType();
ConstructorInfo ctor=t.GetConstructor(new Type[] { t });
if (ctor!=null)
{
ctor.Invoke(new object[] { other });
}
return default(T);
}
}

编辑1

如果你关心速度(每次都做一个反射) ,你可以 a)将构造函数缓存到静态字典中。

public static class Factory
{
public static T Clone<T>(this T other) where T : DrawingObject
{
return Dynamic<T>.CopyCtor(other);
}
}


public static class Dynamic<T> where T : DrawingObject
{
static Dictionary<Type, Func<T, T>> cache = new Dictionary<Type,Func<T,T>>();


public static T CopyCtor(T other)
{
Type t=other.GetType();
if (!cache.ContainsKey(t))
{
var ctor=t.GetConstructor(new Type[] { t });
cache.Add(t, (x) => ctor.Invoke(new object[] { x }) as T);
}
return cache[t](other);
}
}

我相信我比@johnny5的出色回答有进步。只需在所有类中定义复制构造函数,并在基类中使用 Clone 方法中的反射来查找复制建构子并执行它。我认为这是稍微干净,因为你不需要堆栈句柄克隆覆盖,你不需要 MemberwiseClone () ,这只是在许多情况下太钝的工具。

public abstract class AbstractCloneable : ICloneable
{
public int BaseValue { get; set; }
protected AbstractCloneable()
{
BaseValue = 1;
}
protected AbstractCloneable(AbstractCloneable d)
{
BaseValue = d.BaseValue;
}


public object Clone()
{
var clone = ObjectSupport.CloneFromCopyConstructor(this);
if(clone == null)throw new ApplicationException("Hey Dude, you didn't define a copy constructor");
return clone;
}


}




public class ConcreteCloneable : AbstractCloneable
{
public int DerivedValue { get; set; }
public ConcreteCloneable()
{
DerivedValue = 2;
}


public ConcreteCloneable(ConcreteCloneable d)
: base(d)
{
DerivedValue = d.DerivedValue;
}
}


public class ObjectSupport
{
public static object CloneFromCopyConstructor(System.Object d)
{
if (d != null)
{
Type t = d.GetType();
foreach (ConstructorInfo ci in t.GetConstructors())
{
ParameterInfo[] pi = ci.GetParameters();
if (pi.Length == 1 && pi[0].ParameterType == t)
{
return ci.Invoke(new object[] { d });
}
}
}


return null;
}
}

最后,请允许我大声说出对“可克隆”的支持。如果您使用这个界面,您将会受到样式警察的殴打,因为。NET 框架设计指导原则说不要实现它,因为引用指导原则,“当使用一个对象实现一个类型与 ICloneable,你永远不知道你会得到什么。这使得界面毫无用处。”这意味着你不知道你是否得到了一个深的或浅的副本。这简直是诡辩。这是否意味着不应该使用复制构造函数,因为“您永远不知道您将得到什么?”当然没有。如果您不知道将获得什么,那么这只是类的设计问题,而不是接口的问题。

为了创建具有新引用的深度克隆对象,并避免在最意想不到的地方对对象进行突变,请使用 Serialize/Serialize。

它将允许完全控制可以克隆的内容(使用忽略属性)。这里有两个系统的一些例子。短信。Json 和 Newtonsoft。

// System.Text.Json
public object Clone()
{
// setup
var json = JsonSerializer.Serialize(this);


// get
return JsonSerializer.Deserialize<MyType>(json);
}


// Newtonsoft
public object Clone()
{
// setup
var json = JsonConvert.SerializeObject(this);


// get
return JsonConvert.DeserializeObject<MyType>(json);
}


// Usage
MyType clonedMyType = myType.Clone();