本文介绍了protobuf-net 序列化对象图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有对象 A 和 B 都包含一些字段序列化字段 F,并且都指向同一个可序列化对象 C.protobuf-net 是按引用序列化还是按值序列化?当对象图被反序列化时,protobuf-net 是否为 A.F 和 B.F 生成 2 个单独的对象?我问是因为我想知道序列化是否保留引用相等性.

If I have object A and B both contain some field serialized field F, and both point to the same serializable object C. Does protobuf-net serialize by reference or serialize by value? When the object graph is deserialized, does protobuf-net generate 2 separate objects for A.F and B.F? I'm asking because I want to know if serialization preserves reference equality.

推荐答案

Google 定义的原始protobuf"规范是一个树序列化程序(类似于 XmlSerializer).所以默认你会得到 C 序列化两次,反序列化时会得到两个不同的对象.

The raw "protobuf" spec, a defined by Google, is a tree serializer (like XmlSerializer). So by default you would get C serialized twice, and two different objects when deserialized.

然而,这是一个很常见的问题,以至于在v2"中我将其作为选择加入行为提供;请注意,您应该只将它用于 protobuf-net 到 protobuf-net,因为其他客户端不会期望这种配置(尽管它仍然是一个有效的 protobuf 流).

However, this is such a common question that in "v2" I provide this as an opt-in behaviour; note you should only use this for protobuf-net to protobuf-net, as other clients will not expect this configuration (although it remains a valid protobuf stream).

例如(使用属性,您也可以使用运行时模型代替):

For example (using attributes, bit you can also use a runtime model instead):

[ProtoContract]
public class A {
    ...
    [ProtoMember(5, AsReference=true)]
    public C Foo {get;set;}
}

[ProtoContract]
public class B {
    ...
    [ProtoMember(7, AsReference=true)]
    public C Bar {get;set;}
}

[ProtoContract]
public class C {...}

这将序列化实例一次,在输出中生成唯一的 id.反序列化时,两个地方都会使用同一个对象.

This will serialize the instance once, generating an id unique in the output. When deserialized, the same object will be used in both places.

这篇关于protobuf-net 序列化对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:10