为什么我必须使用[ProtoInclude]?

时间:2010-06-23 08:51:43

标签: protobuf-net

我已经阅读了很多关于protobuf-net中继承功能的问题。 我只是想知道如果我可以像使用[ProtoContract],[ProtoMember]一样使用[DataContract],[DataMember]。为什么我不能使用[KnowType]而不是使用[ProtoInclude]?

我提出这个问题是因为我已经将[DataContract],[DataMember]用于protobuf-net的序列化。没有必要添加“Protobuf-net”。它只使用“System.Runtime.Serialization”。

但是......现在如果我的类需要从某个类继承,我是否必须为[ProtoInclude]属性添加“Protobuf-net”?例如,

using System.Runtime.Serialization;
namespace test
{

[DataContract]
/// [KnowType(typeof(SomeClass))]
/// or
/// [ProtoInclude(100,typeof(SomeClass))]
public class BaseClass
{
   //...
   [DataMember(Order=1)]
   public string BlahBlahBlah {get; set;}
}

[DataContract]
public class ChildClass1 : BaseClass
{
   //...
   [DataMember(Order=1)]
   public string BlahBlahBlah {get; set;}
}
}// end namespace

最后,我想知道我是否有100个孩子班,我不会疯狂地在基类中添加100个[ProtoInclude]标签吗?

请求帮助

VEE

1 个答案:

答案 0 :(得分:4)

编辑:在v2中不再需要它 - 您可以在运行时指定它,或使用DynamicType


原因是protobuf有线格式(由Google设计)不包含任何类型元数据,因此我们需要一些方式来了解我们正在谈论的对象类型。 [KnownType]不提供此信息,并且没有明确的方法可以独立提供健壮的密钥。

实际上,protobuf不支持继承 - protobuf-net通过将子类型视为嵌套消息来避免这种情况。所以ChildClass1实际上是正在传输,好像BlahBlahBlah是子对象的属性,有点像:

message BaseClass {
    optional ChildClass1 ChildClass1 = 1;
    optional SomeOtherSubType SomeOtherSubType = 2;
}
message ChildClass1 {
    optional string BlahBlahBlah = 1;
}

重申它;在“v2”中,您可以选择通过自己的代码在类型模型之外指定此数据。这意味着您不需要装饰所有内容,但仍需要一些机制来将键与类型相关联。