问题
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:
- I can see that the
BaseTypemember of the addedProtoBuf.Meta.MetaTypeis set tonull, causing theeffectiveDatespanmember to not be serialized; if I compile the model, instead, itsBaseTypemember is correctly set toDimensionEntity(though it fails later on as the members areprivate readonlyand thus not accessible by a compiled model); - Of course I can declare
ClearingSiteas a known type ofDimensionEntity, but I can't see why this would be required: I am not serializing aDimensionEntity, I'm serializing (and de-serializing) aClearingSite, and furthermore theDataContractSerializerdoes not require me to addKnownTypetoDimensionEntityif I'm serializing aClearingSite.
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