如何制作从List派生的对象的深层副本

问题描述 投票:3回答:1

我有以下课程:

public partial class AuthorizationSetObject
{
   public AuthorizationObjectList AuthorizationObjects { get; set; }
}

public partial class AuthorizationObject
{
   public string Text { get; set; }
}

public partial class AuthorizationObjectList : List<AuthorizationObject>
{
}

我现在需要AuthorizationSetObject的深层副本。我怎样才能做到这一点?

我试过这样的:

public static bool CopyProperties(object source, object target)
{
    var customerType = target.GetType();
    foreach (var prop in source.GetType().GetProperties())
    {
        var propGetter = prop.GetGetMethod();
        if (propGetter != null)
        {
            PropertyInfo pi = customerType.GetProperty(prop.Name);
            if (pi != null)
                {
                var propSetter = pi.GetSetMethod();
                if (propSetter != null)
                {
                    var valueToSet = propGetter.Invoke(source, null);
                    propSetter.Invoke(target, new[] { valueToSet });
                }
            }
        }
    }
    return true;
}

问题是,AuthorizationObjectList不是真正的深层副本。如果我在深层复制后从目标更改属性“文本”,则源中的“文本”将更改为井。

可能我需要一个像“pi.PropertyType.BaseType.IsGenericType”这样的实现,然后再做一些其他的事情......但是什么?

有人有想法吗?

c# list deep-copy derived
1个回答
0
投票

发布到您问题的评论都指向了正确的方向。问题是,在线

propSetter.Invoke(target, new[] { valueToSet });

valueToSet是一个引用,表示您将同一对象的引用添加到列表中。现在ICloneable到位了。如果valueToSet的类型实现了ICloneable,你可以使用

propSetter.Invoke(target, new[] { valueToSet.Clone() });

相反,它将生成此实例的新深层副本。

© www.soinside.com 2019 - 2024. All rights reserved.