MemberwiseClone 不是进行深度复制的好选择(MSDN http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx):
MemberwiseClone 方法通过创建新的对象来创建浅拷贝
对象,然后将当前对象的非静态字段复制到
新对象。如果字段是值类型,则该字段的逐位副本
场进行。如果字段是引用类型,则引用为
已复制但引用的对象未复制;因此,原来的
对象及其克隆引用同一个对象。
这意味着如果克隆对象具有引用类型公共字段或属性,它们将引用与原始对象的字段/属性相同的内存位置,因此克隆对象中的每个更改都将反映在初始对象中。这不是真正的深复制。
您可以使用 BinarySerialization 创建完全独立的对象实例,请参见 MSDN 页面BinaryFormatter 类 http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx一个序列化的例子。
示例和测试工具:
创建给定对象的深层副本的扩展方法:
public static class MemoryUtils
{
/// <summary>
/// Creates a deep copy of a given object instance
/// </summary>
/// <typeparam name="TObject">Type of a given object</typeparam>
/// <param name="instance">Object to be cloned</param>
/// <param name="throwInCaseOfError">
/// A value which indicating whether exception should be thrown in case of
/// error whils clonin</param>
/// <returns>Returns a deep copy of a given object</returns>
/// <remarks>Uses BInarySerialization to create a true deep copy</remarks>
public static TObject DeepCopy<TObject>(this TObject instance, bool throwInCaseOfError)
where TObject : class
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
TObject clonedInstance = default(TObject);
try
{
using (var stream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, instance);
// reset position to the beginning of the stream so
// deserialize would be able to deserialize an object instance
stream.Position = 0;
clonedInstance = (TObject)binaryFormatter.Deserialize(stream);
}
}
catch (Exception exception)
{
string errorMessage = String.Format(CultureInfo.CurrentCulture,
"Exception Type: {0}, Message: {1}{2}",
exception.GetType(),
exception.Message,
exception.InnerException == null ? String.Empty :
String.Format(CultureInfo.CurrentCulture,
" InnerException Type: {0}, Message: {1}",
exception.InnerException.GetType(),
exception.InnerException.Message));
Debug.WriteLine(errorMessage);
if (throwInCaseOfError)
{
throw;
}
}
return clonedInstance;
}
}
NUnit 测试:
public class MemoryUtilsFixture
{
[Test]
public void DeepCopyThrowWhenCopyInstanceOfNonSerializableType()
{
var nonSerializableInstance = new CustomNonSerializableType();
Assert.Throws<SerializationException>(() => nonSerializableInstance.DeepCopy(true));
}
[Test]
public void DeepCopyThrowWhenPassedInNull()
{
object instance = null;
Assert.Throws<ArgumentNullException>(() => instance.DeepCopy(true));
}
[Test]
public void DeepCopyThrowWhenCopyInstanceOfNonSerializableTypeAndErrorsDisabled()
{
var nonSerializableInstance = new CustomNonSerializableType();
object result = null;
Assert.DoesNotThrow(() => result = nonSerializableInstance.DeepCopy(false));
Assert.IsNull(result);
}
[Test]
public void DeepCopyShouldCreateExactAndIndependentCopyOfAnObject()
{
var instance = new CustomSerializableType
{
DateTimeValueType =
DateTime.Now.AddDays(1).AddMilliseconds(123).AddTicks(123),
NumericValueType = 777,
StringValueType = Guid.NewGuid().ToString(),
ReferenceType =
new CustomSerializableType
{
DateTimeValueType = DateTime.Now,
StringValueType = Guid.NewGuid().ToString()
}
};
var deepCopy = instance.DeepCopy(true);
Assert.IsNotNull(deepCopy);
Assert.IsFalse(ReferenceEquals(instance, deepCopy));
Assert.That(instance.NumericValueType == deepCopy.NumericValueType);
Assert.That(instance.DateTimeValueType == deepCopy.DateTimeValueType);
Assert.That(instance.StringValueType == deepCopy.StringValueType);
Assert.IsNotNull(deepCopy.ReferenceType);
Assert.IsFalse(ReferenceEquals(instance.ReferenceType, deepCopy.ReferenceType));
Assert.That(instance.ReferenceType.DateTimeValueType == deepCopy.ReferenceType.DateTimeValueType);
Assert.That(instance.ReferenceType.StringValueType == deepCopy.ReferenceType.StringValueType);
}
[Serializable]
internal sealed class CustomSerializableType
{
public int NumericValueType { get; set; }
public string StringValueType { get; set; }
public DateTime DateTimeValueType { get; set; }
public CustomSerializableType ReferenceType { get; set; }
}
public sealed class CustomNonSerializableType
{
}
}