Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

protocol buffers - protobuf-net serializing object graph

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...