问题
It does not seem possible to implement protobuf-net serialization for classes that define their sub-types via [ProtoInclude] and implement ProtoBuf.IExtensible :
[ProtoBuf.ProtoInclude(1000, typeof(DerivedClass))]
public partial class BaseClass : ProtoBuf.IExtensible
{
...
private IExtension extensionObject;
IExtension IExtensible.GetExtensionObject(bool createIfMissing)
{
return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
}
}
public partial class DerivedClass : BaseClass, ProtoBuf.IExtensible
{
...
private IExtension extensionObject;
IExtension IExtensible.GetExtensionObject(bool createIfMissing)
{
return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
}
}
var baseObject = new MyClass { ... };
DerivedClass derivedObject;
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, baseObject); // throws runtime exception
stream.Seek(0, SeekOrigin.Begin);
derivedObject = Serializer.Deserialize<DerivedClass>(stream);
}
Attempt to serialize throws runtime exception :
{"IExtensible is not supported in structs or classes with inheritance"} at ProtoBuf.Serializers.TypeSerializer..ctor(TypeModel model, Type forType, Int32[] fieldNumbers, IProtoSerializer[] serializers, MethodInfo[] baseCtorCallbacks, Boolean isRootType, Boolean useConstructor, CallbackSet callbacks, Type constructType, MethodInfo factory)
at ProtoBuf.Meta.MetaType.BuildSerializer()
at ProtoBuf.Meta.MetaType.get_Serializer() at ProtoBuf.Meta.RuntimeTypeModel.Serialize(Int32 key, Object value, ProtoWriter dest) at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value) at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context) at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance) at ...
Specifically what is the purpose of implementing IExtensible ? and what are the consequences of not doing so ?
来源:https://stackoverflow.com/questions/40518369/protobuf-net-iextensible-not-supported-for-inheritance