C#深拷贝几种所遇到的问题

1、二进制

/// 
    /// 二进制序列化深拷贝
    /// 
    /// 
    /// 
    /// 
    public static T DeepCopyByBinary<T>(T obj)
    {
        object retval;
        using (MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            retval = bf.Deserialize(ms);
            ms.Close();
        }
        return (T)retval;
    }

所需要深拷贝的类中如果出现unity定义的变量会报错,需要自己进行一层封装,如:Vector3类型。

2、xml

/// 
    /// xml深拷贝
    /// 
    /// 
    /// 
    /// 
    public static T DeepCopyByXml<T>(T obj)
    {
        object retval;
        using (MemoryStream ms = new MemoryStream())
        {
            XmlSerializer xml = new XmlSerializer(typeof(T));
            xml.Serialize(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            retval = xml.Deserialize(ms);
            ms.Close();
        }
        return (T)retval;
    }

在需要深拷贝的类中不能出现类,否则拷贝失败

3、datacontract

/// 
    /// datacontract深拷贝
    /// 防止引用类型直接赋值
    /// 
    /// 
    /// 
    /// 
    public static T DeepCopyByDataContract<T>(T obj)
    {
        object retval;
        using (MemoryStream ms = new MemoryStream())
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(T));
            ser.WriteObject(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            retval = ser.ReadObject(ms);
            ms.Close();
        }
        return (T)retval;
    }

暂未发现、后续补充。

你可能感兴趣的:(c#,开发语言)