[英]How to make a deep copy of an object which is derived from a List<T>
我有以下课程:
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”这样的实现,然后再做一些其他的事情......但是什么?
有人有想法吗?
发布到您问题的评论都指向了正确的方向。 问题是,在线
propSetter.Invoke(target, new[] { valueToSet });
valueToSet是一个引用,表示您将同一对象的引用添加到列表中。 现在ICloneable到位了。 如果valueToSet的类型实现了ICloneable ,则可以使用
propSetter.Invoke(target, new[] { valueToSet.Clone() });
相反,它将生成此实例的新深层副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.