【问题标题】:Protobuf-net serialization issueProtobuf-net 序列化问题
【发布时间】:2013-01-30 22:39:22
【问题描述】:

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

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

【问题讨论】:

    标签: c# protobuf-net


    【解决方案1】:

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

    这样想:

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

    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的字节数组

    【讨论】:

    • 这是正确的。为了一个简单的例子,我过度简化了我的实际问题。我实际上使用数据合约。我有一个具有 2 个属性的类引用其他类。我忘记在引用的类中包含数据成员属性的 Order 属性。所以这就是它没有序列化任何东西的原因。
    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多