克隆对象
public static T DeepCloneObject<T>(this T t) where T : class
{
T model = System.Activator.CreateInstance<T>();
PropertyInfo[] propertyInfos = model.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(t),
nullableConverter.UnderlyingType), null);
}
else
{
propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(t),
propertyInfo.PropertyType), null);
}
}
return model;
}
克隆集合
public static IList<T> DeepCloneList<T>(this IList<T> tList) where T : class
{
IList<T> listNew = new List<T>();
foreach (var item in tList)
{
T model = System.Activator.CreateInstance<T>();
PropertyInfo[] propertyInfos = model.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType);
propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(item),
nullableConverter.UnderlyingType), null);
}
else
{
propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(item),
propertyInfo.PropertyType), null);
}
}
listNew.Add(model);
}
return listNew;
}