如何在没有引用的情况下创建类对象的副本
本文关键字:情况下 创建 对象 副本 引用 | 更新日期: 2023-09-27 18:11:11
如何创建一个没有任何引用的类对象的副本?ICloneable
复制类对象(通过浅复制),但不支持深复制。我正在寻找一个函数,是聪明到足以读取类对象的所有成员,并使一个深度复制到另一个对象,而不指定成员名。
我认为这是一个解决方案,基本上写你自己的函数来做到这一点,因为你说的iclonable不做深度复制
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))
{
...;
}