protobuf-net serializing object graph

十年热恋 提交于 2019-12-18 02:18:32

问题


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.


回答1:


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.

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 {...}

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



来源:https://stackoverflow.com/questions/6294295/protobuf-net-serializing-object-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!