基于接口的Protobuf-net序列化

时间:2010-09-15 00:29:36

标签: protobuf-net

我正在使用protobuf-net r282,当我调用Serialize时,我收到InvalidOperationException错误消息“只能处理数据合同类(以及此类列表/数组)”(错误处理对象)“。在调用protobuf-net Serializer.Serialize时,有问题的对象已被强制转换为接口。有办法解决这个问题吗?

以下是代码:

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using ProtoBuf;
using System;

namespace EventStore.Core
{
public interface Message
{
}

public interface Event : Message
{
    Guid Id { get; set; }

    int Version { get; set; }
}

[DataContract]
public class InventoryItemCreated : Event
{
    [DataMember(Order = 1)]
    public Guid Id { get; set; }

    [DataMember(Order = 2)]
    public int Version { get; set; }

    [DataMember(Order = 3)]
    public string Name { get; set; }

    public InventoryItemCreated(Guid id, string name)
    {
        Id = id;
        Name = name;
    }

    public InventoryItemCreated()
    {

    }
}

public class DefaultSerializer
{
    private readonly IFormatter formatter = new BinaryFormatter();

    public byte[] Serialize<T>(T graph) where T : class
    {
        if (default(T) == graph)
            return null;

        using (var stream = new MemoryStream())
        {
            this.Serialize(graph, stream);
            return stream.ToArray();
        }
    }

    public virtual void Serialize<T>(T graph, Stream output) where T : class
    {
        this.formatter.Serialize(output, graph);
    }

    public T Deserialize<T>(byte[] serialized) where T : class
    {
        if (null == serialized || 0 == serialized.Length)
            return default(T);

        using (var stream = new MemoryStream(serialized))
            return this.Deserialize<T>(stream);
    }

    public virtual T Deserialize<T>(Stream input) where T : class
    {
        return (T)this.formatter.Deserialize(input);
    }
}

public class ProtoBufSerializer : DefaultSerializer
{
    public override void Serialize<T>(T graph, Stream output)
    {
        Serializer.Serialize<T>(output, graph);
    }

    public override T Deserialize<T>(Stream input)
    {
        return Serializer.Deserialize<T>(input);
    }
}

class Program
{
    static void Main(string[] args)
    {
        ProtoBufSerializer serializer = new ProtoBufSerializer();
        InventoryItemCreated item = new InventoryItemCreated(Guid.NewGuid(), "Widget");
        byte[] buffer = serializer.Serialize((Message)item);
    }
}

}

1 个答案:

答案 0 :(得分:0)

这是我一直在寻找的“v2”,但它不完整。我已经为v1发送了一个补丁来执行此操作,我可以分享,但我没有对此进行严格测试。如果你想要这个补丁文件,请告诉我。