问题
I got a source code of Protobuf-net that serializes an object to a file.
var person = new Person {
Id = 12345, Name = "Fred",
Address = new Address {
Line1 = "Flat 1",
Line2 = "The Meadows"
}
};
using (var file = File.Create("person.bin")) {
ProtoBuf.Serializer.Serialize(file, person);
}
But suppose i have two instance of Person that i want to serialize into a single file. how can i do that?
回答1:
protobuf, in the pure sense, does not have any "terminator" except the end of a file (this is so that objects can be merged/combined simply by concatenating the blobs).
However, we can inject our own markers, for example by prefixing every object with the length of the data that follows.
protobuf-net wraps this up by exposing a SerializeWithLengthPrefix
method. There are various methods to deserialize from this, but the simplest is DeserializeItems
, which gives you a streaming sequence of objects in turn (lazily spooling from the stream in the iterator - so it is perfectly suitable for very large sequences).
For info, so you can see how this is implemented: if you use PrefixStyle.Base128
and a positive fieldNumber
, then on the wire this looks the same as if you had a wrapper object like:
[ProtoContract]
public class DoesNotExist {
[ProtoMember({fieldNumber})]
public List<Person> People {get;set;}
}
the key differences being that no actual DoesNotExist
type/instance exists, and no List<T>
is created - you just get the Person
instances.
来源:https://stackoverflow.com/questions/15265698/how-to-append-object-to-a-file-while-serializing-using-c-sharp-protobuf-net