4

我正在使用 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);
    }
}

}

4

1 回答 1

0

这是我一直在寻找“v2”的东西,但它不完整。我已经收到了一个 v1 的补丁,我可以分享这个补丁,但我没有严格测试过。如果你想要这个补丁文件,请告诉我。

于 2010-09-16T05:25:00.077 回答