【发布时间】:2017-07-12 18:01:08
【问题描述】:
我正在使用下面的类来做没有序列化的深度克隆。
public class AbstractClone
{
public AbstractClone Clone()
{
Type typeSource = this.GetType();
AbstractClone tObject = (AbstractClone)FormatterServices.GetUninitializedObject(typeSource);
PropertyInfo[] propertyInfo = typeSource.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo property in propertyInfo)
{
if (property.CanWrite)
{
if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String)))
{
property.SetValue(tObject, property.GetValue(this, null), null);
}
else
{
object objPropertyValue = property.GetValue(this, null);
if (objPropertyValue == null)
{
property.SetValue(tObject, null, null);
}
else
{
property.SetValue(tObject, ((AbstractClone)objPropertyValue).Clone(), null);
}
}
}
}
return tObject;
}
}
我继承了所有需要克隆的类。
这适用于除键值对或 SortedList、Dictionary 等集合之外的所有对象
谁能建议一种方法来克隆 KeyValue 对,例如 Dictionary 的 SortedList。
【问题讨论】:
标签: c# reflection cloning