最简单的 protobuf-net 示例 4 所需的帮助 [英] Help needed with the most trivial protobuf-net example 4
问题描述
[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?
谢谢.
推荐答案
它失败是因为 protobuf-net 无法处理继承,除非您通过属性或运行时类型模型为其提供更多线索 - 本质上它需要从某处(即您)获取字段编号.我很满意地承认,在这种情况下,跟踪警告可能会有用,因为合理很清楚,这种继承场景可能不仅仅是 J
.
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));
(2
的唯一意义在于它不与为 I
定义的任何其他字段冲突).
(the only significance of 2
there is that it doesn't conflict with any other fields defined for I<int>
).
这篇关于最简单的 protobuf-net 示例 4 所需的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!