对象深层克隆实现

use*_*007 3 c# recursion extension-methods deep-copy

我必须实现通用扩展deepclone方法,该方法可以与任何引用类型实例一起使用以获取其深层副本。我实现如下

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它运作良好。但是,如果要克隆的对象及其引用类型字段具有相互引用,则此代码将导致无限循环。例如

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; }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何执行此任务?应该从字面上实现它,不允许有任何变化(这是一种实践)。非常感谢您提供的任何提示!

rai*_*r33 5

深度克隆对象的一个​​老技巧是序列化和反序列化它们,从而创建新实例。

public T deepClone<T>(T toClone) where T : class
{
    string tmp = JsonConvert.SerializeObject(toClone);
    return JsonConvert.DeserializeObject<T>(tmp);            
}
Run Code Online (Sandbox Code Playgroud)

我与之进行了广泛的合作Newtonsoft.Json,它为您的问题提供了内置的解决方案。默认情况下,它检测对象是否已被序列化并引发异常。但是,您可以将其配置为序列化对对象的引用,以避开循环引用。它不是序列化序列化对象,而是序列化对该对象的引用,并保证对一个对象的每个引用仅序列化一次。

此外,默认设置是仅序列化公共字段/属性。还有一个用于序列化私有字段的附加设置。

public T deepClone<T>(T toClone) where T : class
{
    JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

    DefaultContractResolver dcr = new DefaultContractResolver();
    dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
    settings.ContractResolver = dcr;

    string tmp = JsonConvert.SerializeObject(toClone, settings);
    return JsonConvert.DeserializeObject<T>(tmp);
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以“作弊”并使用类似的代码,也可以复制其工作方式以实现保留引用的克隆。您给父母/孩子提供的示例只是克隆困难的一种方法。一对多就是另一个。