Help needed with the most trivial protobuf-net example 4

你。 提交于 2019-12-11 08:06:30

问题


  [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.


回答1:


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>).



来源:https://stackoverflow.com/questions/6285755/help-needed-with-the-most-trivial-protobuf-net-example-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!