Does protocol buffers support serialization of object graphics with shared links?

Please pay attention to the following simple program (based on an example from the protobuf-net v1 wiki project):

using System.Collections.Generic; using System.Diagnostics; using System.IO; using ProtoBuf; namespace HelloProtoBuf { [ProtoContract] class Person { [ProtoMember(1)] public int Id { get; set; } [ProtoMember(2)] public string Name { get; set; } [ProtoMember(3)] public Address Address { get; set; } } [ProtoContract] class Address { [ProtoMember(1)] public string Line1 { get; set; } [ProtoMember(2)] public string Line2 { get; set; } } class Program { static void Main(string[] args) { var person = new Person { Id = 12345, Name = "Fred", Address = new Address { Line1 = "Flat 1", Line2 = "The Meadows" } }; var person2 = new Person { Id = 4553, Name = "Nadya", Address = person.Address }; var persons = new List<Person> { person, person2 }; Debug.Assert(ReferenceEquals(persons[0].Address, persons[1].Address)); using (var file = File.Create("persons.bin")) { Serializer.Serialize(file, persons); } List<Person> persons2; using (var file = File.OpenRead("persons.bin")) { persons2 = Serializer.Deserialize<List<Person>>(file); } Debug.Assert(ReferenceEquals(persons2[0].Address, persons2[1].Address)); } } } 

The second statement fails. Is this a bug in the implementation of protobuf-net or is it that protocol buffers simply do not support graphical objects with shared links?

Thanks.

+6
source share
1 answer

buffer protocol itself does not support this - so no, this is not an error. In fact, XmlSerializer and DataContractSerializer * will do the same (and probably it will be JavaScriptSerializer and JSON.NET).

However, this is a general request, so this one is supported in protobuf-net v2 (basically: I'm cheating). Just change it to:

  [ProtoMember(3, AsReference=true)] public Address Address { get; set; } 

(and use the v2 dll, which I download in about 5 minutes or create from code)


* = caveat: DataContractSerializer supports links, but only if you use a specific constructor; it is disabled by default.

+8
source

Source: https://habr.com/ru/post/888578/


All Articles