在类层次结构中实现ICloneable
的正确方法是什么?假设我有一个抽象类DrawingObject
。另一个抽象类RectangularObject
继承自DrawingObject
。然后有多个具体类,如Shape
、Text
、Circle
等,它们都继承自RectangularObject
。我想在DrawingObject
上实现ICloneable
,然后将其向下传递到层次结构中,在每个级别复制可用属性,并在下一级别调用父级的Clone
。
然而,问题是,由于前两个类是抽象的,我无法在Clone()
方法中创建它们的对象。因此,我必须在每个具体类中复制属性复制过程。或者有更好的方法吗?
您可以使用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();
}
}
为基类提供一个受保护且可重写的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());
}
为了创建具有新引用的深度克隆对象,并避免对象在最意想不到的地方发生突变,请使用Serialize/Desolialize。
它将允许完全控制可以克隆的内容(使用忽略属性)。这里有一些System.Text.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();
我相信我比@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;
}
}
最后让我发言支持ICloneable。如果你使用这个接口,你会被风格警察殴打,因为.NET Framework设计指南说不要实现它,因为引用指南的话,"当使用一个实现ICloneable类型的对象时,你永远不知道你会得到什么。这会使接口变得无用。"这意味着你不知道你得到的是深层副本还是浅层副本。这简直是狡辩。这是否意味着永远不应该使用复制构造函数,因为"你永远不知道你会得到什么?"当然不是。如果你不知道你会得到什么,这只是一个类的设计问题,而不是接口问题。
在我看来,最清晰的方法是在MemoryStream
中使用BinaryFormatter
应用二进制序列化。
在C#中有一个关于深度克隆的MSDN线程,建议使用上面的方法。
至少只允许具体类处理克隆,抽象类具有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);
}
}
这是我几年前写的一些示例代码的复制粘贴。
如今,我避免了使用需要克隆支持的设计;我发现大多数这样的设计都有些古怪。相反,我大量使用了不可变类,从一开始就避免了克隆的需要。
话虽如此,以下是示例克隆模式:
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;
}
}
}
}