最简单的 protobuf-net 示例 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);
}
}
}
为什么断言失败以及如何修复它?
谢谢。
[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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它失败是因为 protobuf-net 无法处理继承,除非您通过属性或运行时类型模型给它更多线索 - 本质上它需要从某个地方(即您)获取字段号。我很高兴地承认,在这种情况下,跟踪警告可能会很有用,因为很明显,这种继承场景可能不仅仅是
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:
(the only significance of
2
there is that it doesn't conflict with any other fields defined forI<int>
).