如何创建一个没有任何引用的类对象副本?ICloneable
通过浅复制创建类对象的副本,但不支持深复制。我正在寻找一种聪明的函数,它可以读取类对象的所有成员并将其深度复制到另一个对象中,而不需要指定成员名称。
我见过这样的解决方案,基本上是编写自己的函数来完成这个任务,因为你所说的ICloneable无法进行深度复制。
public static T DeepCopy(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
我参考了这个帖子。复制一个类,C#
public static object Clone(object obj)
{
object new_obj = Activator.CreateInstance(obj.GetType());
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
if (pi.CanRead && pi.CanWrite && pi.PropertyType.IsSerializable)
{
pi.SetValue(new_obj, pi.GetValue(obj, null), null);
}
}
return new_obj;
}
您可以根据自己的需求进行调整。例如,
if (pi.CanRead && pi.CanWrite &&
(pi.PropertyType == typeof(string) ||
pi.PropertyType == typeof(int) ||
pi.PropertyType == typeof(bool))
)
{
pi.SetValue(new_obj, pi.GetValue(obj, null), null);
}
或者
if (pi.CanRead && pi.CanWrite &&
(pi.PropertyType.IsEnum || pi.PropertyType.IsArray))
{
...;
}