以下代码片段尝试序列化项目并使用它进行反序列化是接口。 请解释如何反序列化从接口继承的类型,如示例
class Program
{
static void Main()
{
Item item = new Item { A = 123321 };
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms item);
ms.Position = 0;
Serializer.Deserialize<IItem>(ms);
}
}
}
ProtoInclude(100 typeof(Item))
public interface IItem
{
int A { get; set; }
}
public class Item : IItem
{
ProtoMember(1)
public int A { get; set; }
}
提出错误:
The type can't be Updated once a serializer has been produced for test.Item >(test.IItem) at ProtoBuf.Meta.RuntimeTypeModel.GetKey(Type type Boolean demand Boolean getBaseKey) in C:\Dev\protobuf-net\protobuf-net\Meta\RuntimeTypeModel.cs:line 388 at ProtoBuf.Meta.RuntimeTypeModel.GetKeyImpl(Type type) in C:\Dev\protobuf-net\protobuf-net\Meta\RuntimeTypeModel.cs:line 362 at ProtoBuf.Meta.TypeModel.GetKey(Type& type) in C:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 982 at ProtoBuf.Meta.TypeModel.DeserializeCore(ProtoReader reader Type type Object value Boolean noAutoCreate) in C:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 576 at ProtoBuf.Meta.TypeModel.Deserialize(Stream source Object value Type type SerializationContext context) in C:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 506 at ProtoBuf.Meta.TypeModel.Deserialize(Stream source Object value Type type) in C:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 488 at ProtoBuf.Serializer.DeserializeT(Stream source) in C:\Dev\protobuf-net\protobuf-net\Serializer.cs:line 69 at test.Program.Main() in ...
答案 0 :(得分:2)
基本上,目前,界面支持适用于属性/列表等,但不适用于根对象。所以你需要一个具体的根类型。除此之外 - 它基本上是 - 我将ProtoMember(1)
移动到界面,感觉更自然 - 但是:
using System.IO;
using ProtoBuf;
class Program
{
static void Main()
{
Item item = new Item { A = 123321 };
var obj = new Wrapper { Item = item };
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, obj);
ms.Position = 0;
IItem iObj = Serializer.Deserialize<Wrapper>(ms).Item;
Item cObj = (Item)iObj;
}
}
}
[ProtoContract]
class Wrapper
{
[ProtoMember(1)]
public IItem Item { get;set; }
}
[ProtoContract]
[ProtoInclude(2, typeof(Item))]
public interface IItem
{
[ProtoMember(1)]
int A { get; set; }
}
[ProtoContract]
public class Item : IItem
{
public int A { get; set; }
}