protobuf-net 将集合合并到现有文件
我已使用 protobuf-net 将集合序列化为文件。
我正在寻找一种将更多项目合并到现有文件中的方法。
目前我有这个:
[Test]
public void CanAppend()
{
var list = new List<Person>();
for (int i = 0; i < 1000; i++)
list.Add(new Person {Name = i.ToString(), Age = i});
using (var file = File.Create("person.bin"))
{
Serializer.Serialize<List<Person>>(file, list);
}
list.Clear();
for (int i = 1000; i < 2000; i++)
list.Add(new Person { Name = i.ToString(), Age = i });
using (var file = File.OpenRead("person.bin"))
{
Serializer.Merge<List<Person>>(file, list);
}
using (var file = File.OpenRead("person.bin"))
{
list = Serializer.Deserialize<List<Person>>(file);
}
//Fails here
Assert.That(list.Count, Is.EqualTo(2000));
}
[ProtoContract]
class Person
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Age { get; set; }
}
但它不起作用。有什么想法吗?
I have serialized a collection to a file using protobuf-net.
I am looking for a way to merge a few more items to the existing file.
Currently I have this:
[Test]
public void CanAppend()
{
var list = new List<Person>();
for (int i = 0; i < 1000; i++)
list.Add(new Person {Name = i.ToString(), Age = i});
using (var file = File.Create("person.bin"))
{
Serializer.Serialize<List<Person>>(file, list);
}
list.Clear();
for (int i = 1000; i < 2000; i++)
list.Add(new Person { Name = i.ToString(), Age = i });
using (var file = File.OpenRead("person.bin"))
{
Serializer.Merge<List<Person>>(file, list);
}
using (var file = File.OpenRead("person.bin"))
{
list = Serializer.Deserialize<List<Person>>(file);
}
//Fails here
Assert.That(list.Count, Is.EqualTo(2000));
}
[ProtoContract]
class Person
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Age { get; set; }
}
But it doesn't work. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Merge
是反序列化操作(它用于将流作为增量读取到现有对象中)。幸运的是,protobuf 序列只是简单的累加,因此您需要做的就是打开流进行追加(或手动移动到流的末尾),然后调用Serialize
。Merge
is deserialization operation (it is used to read a stream as a delta into an existing object). Fortunately, protobuf sequences are simply additive, so all you need to do is open the stream for append (or manually move to the end of the stream), and then callSerialize
.