【发布时间】:2012-02-26 14:32:34
【问题描述】:
我在 C# 中尝试了不同的深度对象克隆技术,最后找到了一个非常优雅的解决方案,它使用反射并且适用于不可序列化的类型。我只是想知道它是否有问题,以及是否有人有不适用于这种方法的 cmets 或用例。这是代码。感谢 cmets!
public static T Clone<T>(this T source)
{
// Get the type
Type type = source.GetType();
T clone = (T)Activator.CreateInstance(type);
// Loop through the properties
foreach (PropertyInfo pInfo in type.GetProperties())
{
pInfo.SetValue(clone, pInfo.GetValue(source, null), null);
}
// Loop through the fields
foreach (FieldInfo fInfo in type.GetFields())
{
fInfo.SetValue(clone, fInfo.GetValue(source).Clone());
}
return clone;
}