1. 程式人生 > 其它 >C# 利用反射和遞迴,深度克隆物件例項

C# 利用反射和遞迴,深度克隆物件例項

/// <summary>
/// 深度克隆物件
/// </summary>
/// <typeparam name="T"></typeparam>
public class TransExpV1<T>
{
public static T Trans(T t)
{
dynamic ret = (T)Activator.CreateInstance(typeof(T));
foreach (var item in typeof(T).GetProperties())
{
if (!item.CanWrite)
continue;

if (item.PropertyType.BaseType == typeof(ValueType))
{
item.SetMethod.Invoke(ret, new[] { item.GetValue(t) });
}
else
{
var type = typeof(TransExpV1<>).MakeGenericType(item.PropertyType);
var aContext = Activator.CreateInstance(type);
var tIn = item.GetValue(t);
var val = aContext.GetType().GetMethod("Trans")
?.Invoke(aContext, new[]
{
tIn
});
item.SetMethod.Invoke(ret, new[] { val });
}
}
return ret;
}
}