protobuf-net 将集合合并到现有文件

发布于 2024-09-13 18:26:59 字数 1033 浏览 6 评论 0原文

我已使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淤浪 2024-09-20 18:26:59

Merge反序列化操作(它用于将流作为增量读取到现有对象中)。幸运的是,protobuf 序列只是简单的累加,因此您需要做的就是打开流进行追加(或手动移动到流的末尾),然后调用Serialize

using (var file = File.Open("person.bin", FileMode.Append, FileAccess.Write)) {
    Serializer.Serialize(file, list);
}

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 call Serialize.

using (var file = File.Open("person.bin", FileMode.Append, FileAccess.Write)) {
    Serializer.Serialize(file, list);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文