【发布时间】:2016-01-27 18:44:23
【问题描述】:
我正在编写一个 C# 表单应用程序,我正在使用以下代码克隆对象:
public static class ObjectExtension
{
public static object CloneObject(this object objSource)
{
//Get the type of source object and create a new instance of that type
Type typeSource = objSource.GetType();
object objTarget = Activator.CreateInstance(typeSource);
//Get all the properties of source object type
PropertyInfo[] propertyInfo = typeSource.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//Assign all source property to taget object 's properties
foreach (PropertyInfo property in propertyInfo)
{
//Check whether property can be written to
if (property.CanWrite)
{
//check whether property type is value type, enum or string type
if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String)))
{
property.SetValue(objTarget, property.GetValue(objSource, null), null);
}
//else property type is object/complex types, so need to recursively call this method until the end of the tree is reached
else
{
object objPropertyValue = property.GetValue(objSource, null);
if (objPropertyValue == null)
{
property.SetValue(objTarget, null, null);
}
else
{
property.SetValue(objTarget, objPropertyValue.CloneObject(), null);
}
}
}
}
return objTarget;
}
}
我的一些对象有父对象,而这些父对象有集合。因此,我收到以下异常:
“System.StackOverflowException”类型的未处理异常 发生在CustomWebpageObjectCreator.exe中
如何防止这种情况发生?
是否可以使用属性来装饰对象中的某些特定属性,以使 CloneObject 代码不会尝试克隆该属性?如果是这样,有人可以帮我写代码吗?如果没有,我应该如何修改我的代码?
【问题讨论】:
-
stackoverflow 发生是因为您的属性是递归的,即对象 A 可能具有对对象 B 的引用,而对象 B 又具有对对象 A 的引用,因此它们不断尝试彼此序列化。您绝对可以使用属性执行此操作,请查看 MSDN 中的 GetCustomAttributes 文档
-
标准解决方案是序列化/反序列化 - stackoverflow.com/questions/78536/deep-cloning-objects... 循环引用很难处理,您最好使用现有解决方案。
标签: c# reflection clone