C# 中的深度克隆对象
我在 C# 中尝试了不同的深度对象克隆技术,最终找到了非常优雅的解决方案,该解决方案使用反射并适用于不可序列化类型。我只是想知道它是否有问题,以及是否有人有不适用于此方法的评论或用例。这是代码。感谢您的评论!
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;
}
I was playing with different techniques for deep object cloning in C#, and finally came to pretty elegant solution that uses reflection and is applicable for non-serializable types. I am just wondering is there something wrong with it, and if anybody has comments or use case that does not work with this approach. Here is the code. Thanks for comments!
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以看到几个问题:
There are several issues I can see:
如果没有可访问的无参数构造函数怎么办?
如果存在无法共享的成员对象(可能是文件句柄)怎么办?
那么非公众成员呢?
为什么需要为一个不存在的问题创建一个通用的解决方案(您不需要能够深度克隆所有内容!)?
What if there is no accessible parameterless constructor?
What if there is an member object that can't be shared (a file handle, maybe)?
What about non-public members?
Why the need to create a one-size fits all solution to a problem that doesn't exist (you don't need to be able to deep clone everything!)?