使用C#protobuf-net进行序列化时,如何将对象附加到文件? [英] How to append object to a file while serializing using c# protobuf-net?
问题描述
我得到了Protobuf-net的源代码,该源代码将对象序列化为文件.
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);
}
但是假设我有两个要序列化为单个文件的Person实例.我该怎么办?
纯粹意义上,protobuf除文件末尾外没有任何终止符"(这是因为对象可以通过以下方式简单地合并/合并:连接斑点).
但是,我们可以插入自己的标记,例如,通过在每个对象前添加随后的数据长度作为前缀.
protobuf-net通过公开SerializeWithLengthPrefix
方法对此进行了总结.有多种方法可以反序列化此方法,但是最简单的方法是DeserializeItems
,它依次为您提供对象的流序列(从迭代器的流中懒惰地假脱机-因此非常适合非常大的序列).>
有关信息,因此您可以看到它是如何实现的:如果使用PrefixStyle.Base128
和正数fieldNumber
,则在线看起来就好像您有包装对象一样像:
[ProtoContract]
public class DoesNotExist {
[ProtoMember({fieldNumber})]
public List<Person> People {get;set;}
}
主要区别在于没有实际的DoesNotExist
类型/实例,并且没有创建List<T>
-您只需获取Person
实例.
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?
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.
这篇关于使用C#protobuf-net进行序列化时,如何将对象附加到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!