【发布时间】:2020-04-23 02:32:59
【问题描述】:
我正在使用 Protobuf-NET 反序列化协议缓冲区数据,并且正在处理多个相同但扩展名略有不同的 Proto 文件。基本上每个 Proto 提要 99% 相同,然后提供 1 或 2 个彼此不同的字段作为每个字段的扩展。所以我最终得到了多个 99% 相同的 Proto 类。
从逻辑上讲,我想为生成的 C# proto 文件添加继承,以避免 99% 的冗余代码解析每个提要。问题是我在反序列化时收到以下错误:
System.NotSupportedException
HResult=0x80131515
Message=IExtensible is not supported in structs or classes with inheritance
Source=protobuf-net
StackTrace:
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) in C:\code\protobuf-net\src\protobuf-net\Serializers\TypeSerializer.cs:line 97
at ProtoBuf.Meta.MetaType.BuildSerializer() in C:\code\protobuf-net\src\protobuf-net\Meta\MetaType.cs:line 480
at ProtoBuf.Meta.MetaType.get_Serializer() in C:\code\protobuf-net\src\protobuf-net\Meta\MetaType.cs:line 372
at ProtoBuf.Meta.RuntimeTypeModel.Deserialize(Int32 key, Object value, ProtoReader source) in C:\code\protobuf-net\src\protobuf-net\Meta\RuntimeTypeModel.cs:line 802
at ProtoBuf.Meta.TypeModel.DeserializeCore(ProtoReader reader, Type type, Object value, Boolean noAutoCreate) in C:\code\protobuf-net\src\protobuf-net\Meta\TypeModel.cs:line 718
at ProtoBuf.Meta.TypeModel.Deserialize(Stream source, Object value, Type type, SerializationContext context) in C:\code\protobuf-net\src\protobuf-net\Meta\TypeModel.cs:line 590
at ProtoBuf.Serializer.Deserialize[T](Stream source) in C:\code\protobuf-net\src\protobuf-net\Serializer.cs:line 68
因此,似乎不支持这种情况。现在尚不清楚这是否适用于基类或派生类中的 IExtensible 用法。基类必须保持可扩展,因为我应用了多个扩展,但扩展/派生类不能。
我的代码类似于下面的代码,取自this post。 现在在任何人将其标记为“重复”之前 - 这并不是因为我的问题完全不同。虽然它的 OP 询问 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);
}
问题:如何实现上述场景的继承?我愿意修改派生类、您可以建议的任何其他工作,甚至使用另一个 .NET Protobuf 库。
【问题讨论】:
标签: c# inheritance protocol-buffers protobuf-net