2
下面的代碼片段試圖序列化一個項目,並使用它的反序列化是接口。 請給予解釋我如何序列化從接口繼承類型,如在例如無法反序列化接口的類型
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 ...
錯誤消息告訴你到底是什麼問題...你必須重新創建IItem類型的串行器。此外,你確定Protobuf能夠處理接口? –
爲什麼沒有人讀過例外!它包含了所有你需要的信息...... – Liam
串行器的使用不會假設爲特定類型創建或重新創建串行器 - 它是作爲靜態類中的靜態方法實現的。 – Danyl