我需要实现一个通用的扩展深拷贝方法,可以用于任何引用类型实例来获得它的深度副本。我将其实现如下:
static class ClassCopy
{
static public T DeepClone<T> (this T instance)
{
if (instance == null) return null;
var type = instance.GetType();
T copy;
var flags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance;
var fields = type.GetFields(flags);
// If type is serializable - create instance copy using BinaryFormatter
if (type.IsSerializable)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, instance);
stream.Position = 0;
copy = (T) formatter.Deserialize(stream);
}
// Copy all fiels which are not marked as serializable
foreach (var field in fields)
{
if (!field.IsNotSerialized) continue;
var value = field.GetValue(instance);
//Recursion!!!
//for each embedded object also create deep copy
value = value != null ? value.DeepClone() : value;
field.SetValue(copy, value);
}
}
else
{
// If type is not serializable - create instance copy using Activator
//(if there is default constructor)
// or FormatterServices ( if there is no constractor)
copy = CreateInstance<T>(type);
foreach (var field in fields)
{
var value = field.GetValue(instance);
//Recursion!!!
value = value != null ? value.DeepClone() : value;
field.SetValue(copy, value);
}
}
//Copy all properties
//In order to copy all backing fields for auto-implemented properties
var properties = type.GetProperties(flags|BindingFlags.SetProperty);
foreach (var property in properties)
{
if (property.CanWrite)
{
var value = property.GetValue(instance);
//Recursion!!!
value = value != null ? value.DeepClone() : null;
property.SetValue(copy, value);
}
}
return copy;
}
private static T CreateInstance<T>(Type t) where T: class
{
T instance;
var constructor = t.GetConstructor(Type.EmptyTypes);
if (constructor != null)
{
instance = Activator.CreateInstance(t) as T;
return instance;
}
instance = FormatterServices.GetUninitializedObject(t) as T;
return instance;
}
}
它可以正常工作。但是,如果要克隆的对象及其引用类型字段存在相互引用关系,则该代码会导致无限循环。
例如:
private static void Main(string[] args)
{
var parent = new Parent();
parent.Child = new Child();
parent.Child.Parent = parent;
//Infinite Loop!!!
var parent1 = parent.DeepClone();
}
class Parent
{
public Child Child { get; set; }
}
class Child
{
public Parent Parent { get; set; }
}
有人知道如何实现这个任务吗?它必须按照字面意思实现,不允许任何变化(这是一个实习)。非常感谢任何提示!