最简单的 protobuf-net 示例 4 需要帮助

发布于 2024-11-14 13:32:44 字数 630 浏览 2 评论 0原文

  [DataContract]
  public class I<TId>
  {
    [DataMember(Order = 1)]
    public TId Id { get; set; }
  }

  [DataContract]
  public class J : I<int>
  {
    [DataMember(Order = 1)]
    public string Description { get; set; }
  }

  class Program
  {
    static void Main()
    {
      var o = new J { Id = 5, Description = "xa-xa", };
      using (var ms = new MemoryStream())
      {
        Serializer.Serialize(ms, o);
        ms.Position = 0;
        var o2 = Serializer.Deserialize<J>(ms);
        Debug.Assert(o.Id == o2.Id);
      }
    }
  }

为什么断言失败以及如何修复它?

谢谢。

  [DataContract]
  public class I<TId>
  {
    [DataMember(Order = 1)]
    public TId Id { get; set; }
  }

  [DataContract]
  public class J : I<int>
  {
    [DataMember(Order = 1)]
    public string Description { get; set; }
  }

  class Program
  {
    static void Main()
    {
      var o = new J { Id = 5, Description = "xa-xa", };
      using (var ms = new MemoryStream())
      {
        Serializer.Serialize(ms, o);
        ms.Position = 0;
        var o2 = Serializer.Deserialize<J>(ms);
        Debug.Assert(o.Id == o2.Id);
      }
    }
  }

Why does the assertion fail and how to fix it?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

水波映月 2024-11-21 13:32:44

它失败是因为 protobuf-net 无法处理继承,除非您通过属性或运行时类型模型给它更多线索 - 本质上它需要从某个地方(即您)获取字段号。我很高兴地承认,在这种情况下,跟踪警告可能会很有用,因为很明显,这种继承场景可能不仅仅是 J

以下添加(在运行时)修复了该问题:(

RuntimeTypeModel.Default.Add(typeof(I<int>), true).AddSubType(2, typeof(J));

2 的唯一意义是它不与为 I 定义的任何其他字段冲突)。

It fails because protobuf-net can't process inheritance unless you give it more of a clue either via attributes or a runtime type-model - essentially it needs to get a field number from somewhere (i.e. you). I am content to concede that maybe a trace warning might be useful in this case, since it is reasonably clear that there is probably more to this inheritance scenario than just J.

The following addition (at runtime) fixes it:

RuntimeTypeModel.Default.Add(typeof(I<int>), true).AddSubType(2, typeof(J));

(the only significance of 2 there is that it doesn't conflict with any other fields defined for I<int>).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文