Protobuf-net序列化问题

时间:2013-01-30 22:39:23

标签: c# protobuf-net

这似乎是一个相当简单的用例,我不明白如何抛出以下代码片段中的异常。

static void Main(string[] args)
{
    using (var foobar = new MemoryStream())
    {
        ProtoBuf.Serializer.Serialize(foobar, new Foobar());
        if (foobar.Length == 0)
            throw new Exception("Didn't serialize");
    }
}

[ProtoContract]
public class Foobar
{
    [ProtoMember(1)]
    public int FoobarInt { get; set; }
}

1 个答案:

答案 0 :(得分:1)

ProtoBuf有点奇怪......零长度的序列化形式本身并不是“错误”......

这样想:

如果你想* de *序列化一个流并获得你试图序列化的空对象,空流就足够了(即,对象的“new”会做同样的事情)但是如果有任何数据集在对象上,现在你需要实际保存/加载东西

static void Main(string[] args)
{
    using (var foobar = new MemoryStream())
    {
        var foo = new Foobar() { FoobarInt = 1 };
        ProtoBuf.Serializer.Serialize(foobar, foo);
        if (foobar.Length == 0)
            throw new Exception("Didn't serialize");
    }
}

[ProtoContract]
public class Foobar
{
    [ProtoMember(1)]
    public int FoobarInt { get; set; }
}

现在生成一个0x08, 0x01

的字节数组
相关问题