Why I have to use [ProtoInclude]?

烂漫一生 提交于 2019-12-18 17:02:05

问题


I have read many questions about inheritance feature in protobuf-net. I just wonder that if I can use [DataContract],[DataMember] in the same way of using [ProtoContract],[ProtoMember]. Why I could not use [KnowType] instead of using [ProtoInclude]?

I raise this question because I used [DataContract],[DataMember] for protobuf-net's serialization already. There was no need to add "Protobuf-net". It used only "System.Runtime.Serialization".

But... Now if my class need to inherit from some class, do I have to add "Protobuf-net" for [ProtoInclude] attribute? for example,

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

finally, I wonder if I have 100 child class, Won't I drive myself crazy adding 100 [ProtoInclude] tags inside base class?

Thx in adv for any help

vee


回答1:


EDIT: this is no longer required in v2 - you can specify this at runtime, or use DynamicType.


The reason for this is that the protobuf wire format (devised by Google) does not include any type metadata, and so we need some way of knowing what type of object we are talking about. [KnownType] doesn't provide this information, and there is no clear way of providing a robust key independently.

Actually, protobuf doesn't support inheritance either - protobuf-net shims around that by treating sub-types as nested messages. So a ChildClass1 actually appears in transit as though BlahBlahBlah was a property of a sub-object, a bit like:

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

etc

Re omitting it; in "v2", you have the option of specifying this data outside of the type model, via your own code. This means you don't need to decorate everything, but it still needs some mechanism to associate keys with types.



来源:https://stackoverflow.com/questions/3100207/why-i-have-to-use-protoinclude

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!