protobuf-net 并从通用集合中派生
我无法弄清楚如何让 protobuf-net 序列化从 List< 派生的对象T>。我尝试添加 ProtoInclude 属性,但收到 ProtoBuf.ProtoException : ProtoIncludeAttribute 的已知类型 List`1 必须是 UserTypeCollection 的直接子类。当我删除 ProtoIninclude 属性时,似乎数据根本没有被序列化。我似乎在任何地方都找不到这种情况的任何例子。我添加 protobuf 序列化作为 WS api 的选项,并且需要保持与 DataContractSerializer 的兼容性。
[CollectionDataContract(), ProtoContract(InferTagFromName = true)]
[ProtoInclude(100, typeof(List<UserType>))]
public class UserTypeCollection : List<UserType>
{ ... }
[DataContract(), ProtoContract(InferTagFromName = true)]
public class UserType { ... }
I am having trouble figuring out how to get protobuf-net to serialize an object that derives from List< T >. I have tried adding the ProtoInclude attribute but I receive an ProtoBuf.ProtoException : Known-type List`1 for ProtoIncludeAttribute must be a direct subclass of UserTypeCollection. When I remove the ProtoInclude attrib it appears the data is not being serialized at all. I can not seem to find any examples of this situation anywhere. I am adding protobuf serialization as an option for our WS api and need to maintain compatibility with DataContractSerializer.
[CollectionDataContract(), ProtoContract(InferTagFromName = true)]
[ProtoInclude(100, typeof(List<UserType>))]
public class UserTypeCollection : List<UserType>
{ ... }
[DataContract(), ProtoContract(InferTagFromName = true)]
public class UserType { ... }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ProtoInclude
用于表示 sub 类型,而不是基本类型(毕竟基本类型是已知的)。此外,IList
处理应该在很大程度上是隐式的;请注意,“推断...”等在列表的情况下作用很小,因为列表只是所包含项目的序列。对于以下内容,我假设您正在尝试序列化列表(作为最顶层的对象):
我目前不在正确的机器上,但在已发布的dll中,我期望通过对象包装列表可以使其工作:
在“v2”中,我希望这种情况从一开始就有效。明天我会尝试测试一下(当我有合适的机器时)。
另一种想法是:子类化
List
通常不是很有用,因为没有一个方法是虚拟的。当然,取决于你。最后一点 - 在“v2”中,如果您想对序列化有更多控制,但又不影响类型本身,我们可以在外部描述模型。ProtoInclude
is used to denote sub types, not base types (after all, the base-type is already known). Also, theIList<T>
handling should largely be implicit; note that the "infer..." etc do very little in the case of lists, since lists are just a sequence of the contained items.For the following, I'm assuming that you are trying to serialize the list (as the top-most object):
I'm not on the right machine at the moment, but in the released dlls, I would expect that wrapping the list via an object would make it work:
In "v2" I would hope that this scenario works from the outset. I'll try to test this tomorrow (when I'll have the right machine).
One other thought; subclassing
List<T>
isn't usually very useful, since none of the methods are virtual. Up to you, of course. And a final note - in "v2" we can describe the model externally if you want to have more control over the serialization but without impacting the types themselves.