如何在没有任何引用的情况下创建类对象的副本?

时间:2011-10-14 13:34:20

标签: c# asp.net

如何在没有任何引用的情况下创建类对象的副本? ICloneable制作类对象的副本(通过浅拷贝),但不支持深度复制。我正在寻找一个足够聪明的函数来读取类对象的所有成员,并在不指定成员名的情况下对另一个对象进行深层复制。

2 个答案:

答案 0 :(得分:4)

我已经看到这是一个解决方案,基本上编写自己的函数来执行此操作,因为您所说的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);
    }
}

我正在引用这个帖子。 copy a class, C#

答案 1 :(得分:0)

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);
}

OR

if (pi.CanRead && pi.CanWrite && 
    (pi.PropertyType.IsEnum || pi.PropertyType.IsArray))
{
    ...;
}