【发布时间】:2021-07-10 16:11:57
【问题描述】:
序列化时获取“意外的子类型”。
var model = RuntimeTypeModel.Create();
var baseType = model.Add(typeof(BaseClass), true, CompatibilityLevel.Level300);
var child = baseType.AddSubType(10, typeof(ChildOfBase));
child.AddSubType(20, typeof(GrandChildToBase));
using (var stream = new MemoryStream())
{
model.Serialize(stream, grandChildInstance); //ERROR : Unexpected sub type GrandChildToBase
}
获取“意外的子类型 GrandChildToBase” 注意:虽然我将 CompatLevel 设置为 300,但它默认为 200。 我在版本 3.0.101
我不想在 BaseClass 上使用“ProtoInclude”。 (我所有的类都是通过 nuget 包独立分发的,并且知道基类中断中的子类)
编辑 1 序列化现在正在工作! (感谢马克格雷维尔) 但是,反序列化不是(获取“无法将 BaseClass 类型的对象转换为 GrandChildToBase”)..
var model = RuntimeTypeModel.Create();
model.DefaultCompatibilityLevel = CompatibilityLevel.Level300;
var baseType = model.Add(typeof(BaseClass));
var childType = model.Add(typeof(ChildOfBase));
model.Add(typeof(GrandChildToBase)); // don't need to capture result of this one
baseType.AddSubType(10, typeof(ChildOfBase));
childType.AddSubType(20, typeof(GrandChildToBase));
byte[] result = null;
using (var stream = new MemoryStream())
{
GrandChildToBase grandChildInstance = new();
model.Serialize(stream, grandChildInstance);
result = stream.ToArray();
}
using (var stream = new MemoryStream(result))
{
var payloadObj = Serializer.Deserialize<GrandChildToBase>(stream); ***//ERROR: "Unable to cast object of type BaseClass to GrandChildToBase"***
}
编辑 2 根据@Marc Gravell 的说明,我需要使用自定义“模型”而不是“默认”序列化程序。
【问题讨论】:
-
grandChildInstance声明的 变量 类型是什么? (不是对象/实例类型;变量类型)? -
其类型为“grandChildInstance”
标签: c# protobuf-net