C# 利用反射和递归,深度克隆对象实例


///


/// 深度克隆对象
///

///
public class TransExpV1
{
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;
}
}

C