ProtoBuf-Net错误消息“源数据中的无效字段:0”

时间:2013-01-07 12:59:30

标签: c# serialization deserialization protobuf-net

我成功序列化了以下类的实例,但是当我在收到以下错误消息后尝试反序列化时:" Invalid field in source data: 0"

我不知道它是指什么,因为我直接找到了下面的课程。我刚刚将protobuf-net版本更新为2.00.614(运行时版本:2.0.50727)。

我是否有可能忽略一些微不足道的事情?

[ProtoContract]
public class TimeSeriesProperties 
{
    [ProtoMember(1)]
    public string TimeSeriesName { get; private set; }
    [ProtoMember(2)]
    public string FileName { get; private set; }
    [ProtoMember(3)]
    public string TemplateName { get; private set; }
    [ProtoMember(4)]
    public int PacketLength { get; private set; }
    [ProtoMember(5)]
    public long FileSizeBytes { get; set; }
    [ProtoMember(6)]
    public long NumberRecords { get; set; }
    [ProtoMember(7)]
    public DateTime DateTimeStart { get; set; }
    [ProtoMember(8)]
    public DateTime DateTimeEnd { get; set; }

    public TimeSeriesProperties()
    {

    }

    public TimeSeriesProperties(string timeSeriesName, string fileName, string templateName, int PacketLength)
    {
        this.TimeSeriesName = timeSeriesName;
        this.FileName = fileName;
        this.TemplateName = templateName;
        this.PacketLength = PacketLength;
    }

}

public static byte[] Serialize_ProtoBuf<T>(T serializeThis)
    {
        using (var stream = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize<T>(stream, serializeThis);
            return stream.GetBuffer();
        }
    }

    public static T Deserialize_ProtoBuf<T>(byte[] byteArray)
    {
        using (var stream = new MemoryStream(byteArray))
        {
            return ProtoBuf.Serializer.Deserialize<T>(stream);
        }
    }

1 个答案:

答案 0 :(得分:7)

我见过的最常见原因是GetBuffer()MemoryStream的使用不正确。当我添加评论时,这已经是我的预感了,但你已经证实了这一点:

using (var stream = new MemoryStream())
{
    ProtoBuf.Serializer.Serialize<T>(stream, serializeThis);
    return stream.GetBuffer();
}

GetBuffer返回超大后备缓冲区。它最后有垃圾。使用GetBuffer是完全正常的,您还会记录.Length,其中包含有效数据的数量。这可以避免额外分配潜在的大型阵列。但在您的情况下,更简单的方法可能是使用ToArray()来获取正确大小的缓冲区:

using (var stream = new MemoryStream())
{
    ProtoBuf.Serializer.Serialize<T>(stream, serializeThis);
    return stream.ToArray();
}