Protobuf-net RuntimeTypeModel not serializing members of base class

落爺英雄遲暮 提交于 2019-12-10 10:11:56

问题


Say I have the following base class:

[DataContract]
[Serializable]
public abstract class DimensionEntity
{
    [DataMember(Order = 1)]
    private readonly Date effectiveDatespan;
    ...
}

And the following derived class:

[DataContract]
[Serializable]
public class ClearingSite : DimensionEntity
{
    [DataMember(Order = 1)]
    private readonly string code;
    ...
}

When I serialize an instance of ClearingSite as follows:

        model.Add(typeof(ClearingSite), true);
        model.Serialize(ms, clearingSite);

I can see that only the code member of ClearingSite is serialized; the value of the base class' effectiveDatespan member is not serialized.

Two notes:

  1. I can see that the BaseType member of the added ProtoBuf.Meta.MetaType is set to null, causing the effectiveDatespan member to not be serialized; if I compile the model, instead, its BaseType member is correctly set to DimensionEntity (though it fails later on as the members are private readonly and thus not accessible by a compiled model);
  2. Of course I can declare ClearingSite as a known type of DimensionEntity, but I can't see why this would be required: I am not serializing a DimensionEntity, I'm serializing (and de-serializing) a ClearingSite, and furthermore the DataContractSerializer does not require me to add KnownType to DimensionEntity if I'm serializing a ClearingSite.

From other answers from Marc, it looks like Protobuf would require the KnownType (or ProtoInclude) attribute in order to get the "all-important field-number" (quote), but that seems to not be the case, as the CompiledModel works totally fine without ProtoInclude.

Note that I'm striving to use System.Runtime.Serialization attributes only, as I'm trying to keep my object model unaware of serializers down the road.


回答1:


ProtoInclude, or an equivalent, is definitely required. If something is happening oddly with the compiled version, then that is a bug and I can investigate.

If you don't want to add non-BCL attributes to your type, this can be done at runtime:

RuntimeTypeModel.Default[typeof(BaseType)]
    .AddSubClass(.....);

(or somethig like that - I'm not at a PC)



来源:https://stackoverflow.com/questions/10400539/protobuf-net-runtimetypemodel-not-serializing-members-of-base-class

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