C# 定义继承后Protobuf net反序列化
我正在使用protobuf net版本2.0.0.640序列化一些数据,如下所示C# 定义继承后Protobuf net反序列化,c#,.net,protocol-buffers,protobuf-net,C#,.net,Protocol Buffers,Protobuf Net,我正在使用protobuf net版本2.0.0.640序列化一些数据,如下所示 [ProtoContract(ImplicitFields = ImplicitFields.AllFields)] public interface ITestMessage { } [ProtoContract(ImplicitFields = ImplicitFields.AllFields)] public class MyOrder : ITestMessage { public int Am
[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
public interface ITestMessage
{
}
[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
public class MyOrder : ITestMessage
{
public int Amount { get; set; }
}
[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
public class MyOrderWrapper
{
public MyOrder Order { get; set; }
}
[TestMethod]
public void TestOrderSerialize()
{
var order = new MyOrder() {Amount = 10};
var orderWrapper = new MyOrderWrapper() { Order = order };
using (var file = File.Create("C:\\temp\\order.bin"))
{
Serializer.Serialize<MyOrderWrapper>(file, orderWrapper);
}
}
尝试反序列化以前保存的数据时,我遇到以下错误。
“未找到ITestMessage的无参数构造函数”
[TestMethod]
public void TestOrderDeserialize()
{
RuntimeTypeModel.Default[typeof(ITestMessage)].AddSubType(2,typeof(MyOrder));
MyOrderRapper orderWrapper;
使用(var file=file.OpenRead(“C:\\temp\\order.bin”))
{
orderWrapper=Serializer.Deserialize(文件);
}
}
有人能解释一下为什么当“MyOrderRapper”在继承Hirarch中没有引用任何高于“MyOrder”的东西时会发生这种情况
另外,当我在“ITestMessage”中明确地包含“[ProtoInclude(2,typeof(MyOrder))]”时,为什么它会起作用
感谢基本上,就序列化程序而言,这是一个突破性的变化——在连线层,既不存在“类”也不存在“接口”,因此在存储方面,这类似于改变类的基本类型;序列化时,根类型为
MyOrder
,反序列化时,根类型为ITestMessage
。这不会让它快乐
基本上:您不能这样做。为什么要显式定义属性?还有,有什么建议可以让我绕过这个问题吗?i、 e.读回以前的数据,然后构建一个新模型以包含关系。@Prin您的意思是“当我在“ITestMessage”中明确包含“[ProtoInclude(2,typeof(MyOrder))]”时,为什么它会起作用”-hmm;我必须看一看,但我怀疑这从来都不是模型的一部分;它将自动检测基类型上的契约,但我认为它不会遍历接口,因为这些接口在重要方面的工作方式非常不同
RuntimeTypeModel.Default[typeof(ITestMessage)].AddSubType(2, typeof(MyOrder));
[TestMethod]
public void TestOrderDeserialize()
{
RuntimeTypeModel.Default[typeof(ITestMessage)].AddSubType(2, typeof(MyOrder));
MyOrderWrapper orderWrapper;
using (var file = File.OpenRead("C:\\temp\\order.bin"))
{
orderWrapper = Serializer.Deserialize<MyOrderWrapper>(file);
}
}