Skip to content

ProtoBuf深拷贝问题

Public: Yes Published: 2021/03/12 Tags: C#, Unity

深拷贝某个对象

public static T DeepCopy<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;
        }

当后端proto协议与前端不一致时,此时前端用该对象序列化时,会报错

SerializationException: Type 'ProtoBuf.BufferExtension' in Assembly 'ProtoBuf-Net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers (System.RuntimeType type) (at <9577ac7a62ef43179789031239ba8798>:0)

解决方法:

导入 using ProtoBuf;

使用 Serializer.SerializeWithLengthPrefix 而不是C#自带的 Serialize 方法。

public static T DeepCopy<T>(T obj)
        {
            object retval;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                Serializer.SerializeWithLengthPrefix(ms,obj,PrefixStyle.None);
                //序列化成流
                ms.Seek(0, SeekOrigin.Begin);
                //反序列化成对象
                retval = Serializer.Deserialize<T>(ms);
                ms.Close();
            }
        
            return (T) retval;
        }