protobuf-net proto2 c#
我有一个派生类,通过隐藏同名的基类属性来重新定义类型。
我希望将一个基类实例序列化,并作为派生类型进行反序列化:
[ProtoBuf.ProtoContract(Name=@"BaseClassProto")]
[ProtoBuf.ProtoInclude(typeof(DerivedClass), 1000)]
public partial class BaseClass {
[ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"MyProperty", DataFormat = ProtoBuf.DataFormat.TwosComplement)]
public int MyProperty { get; set; }
}
[ProtoBuf.ProtoContract(Name=@"DerivedClassProto")]
public partial class DerivedClass : BaseClass {
[ProtoBuf.ProtoMember(1, IsRequired = false, Name = @"MyProperty", DataFormat = ProtoBuf.DataFormat.TwosComplement)]
public new MyEnum MyProperty { get; set; }
}
}
public class Test {
var baseObject = new BaseClass{ TestString = "TestBaseObject", TestInt = 1 };
DerivedClass derivedObject;
using (var stream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(stream, baseObject);
Debug.WriteLine(stream.Length);
stream.Seek(0, SeekOrigin.Begin);
derivedObject = ProtoBuf.Serializer.Deserialize<DerivedClass>(stream);
}
}
一个类型为 'System.InvalidCastException' 的异常在 protobuf-net.dll 中发生,但未在用户代码中处理。其他信息:无法将类型为 'BaseClass' 的对象转换为类型 'DerivedClass'。
为什么
protobuf-net
尝试将 BaseClass
转换为 DerivedClass
?根据
DerivedClass
中的 proto 注释,protobuf-net
不应该直接将消息反序列化为 DerivedClass
吗?同时,隐藏
BaseClass.IntProperty
是否也会隐藏它的 ProtoMember
注释?从而允许在 DerivedClass
中重新定义 proto index 1
?添加附加信息:
尝试使用最小可行测试用例,即使将
DerivedClass
重新定义为尽可能简单的形式:[ProtoBuf.ProtoContract(Name=@"DerivedClassProto")]
public partial class DerivedClass : BaseClass {
}
我发现序列化BaseClass
/ 反序列化DerivedClass
仍然会抛出相同的System.InvalidCastException
异常。
如果我反序列化成object
类型的引用(而不是DerivedClass
),底层类型是BaseClass
。这解释了类型转换异常,但是这也引出了一个问题:为什么ProtoBuf.Serializer.Deserialize<DerivedClass>()
反序列化成BaseClass
类型的对象?
[ProtoBuf.ProtoInclude(typeof(MyDerivedType), 1000)]
。 - BaltoStar[ProtoInclude]
的目的是什么? - BaltoStar