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

ton*_*ong 5 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
Run Code Online (Sandbox Code Playgroud)

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

感谢您提供任何帮助

VEE

Mar*_*ell 5

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


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

实际上,protobuf 也不支持继承- protobuf-net 通过将子类型视为嵌套消息来解决这一问题。所以 aChildClass1实际上出现在传输过程中,就好像BlahBlahBlah它是子对象的属性一样,有点像:

message BaseClass {
    optional ChildClass1 ChildClass1 = 1;
    optional SomeOtherSubType SomeOtherSubType = 2;
}
message ChildClass1 {
    optional string BlahBlahBlah = 1;
}
Run Code Online (Sandbox Code Playgroud)

ETC

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