2

The below code snippet tries to serialize an item and de-serialize using it is interface. Please give an explanation how I can deserialize types inherited from the interface like on example

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; }
}

Raise an error:

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 ...
4

1 回答 1

2

Basically, at the current time, interface support works for properties / lists, etc - but does not work for the root object. So you would need a concrete root type. Other than that - it is basically there - I moved the ProtoMember(1) to the interface, which feels more natural - but:

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; }
}
于 2013-11-04T08:37:30.383 回答