简体   繁体   中英

Protobuf-net serialization issue

This seems like a fairly simple use case, I don't understand how the exception in the following code snippet is being thrown.

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

ProtoBuf is kinda weird...a zero-length serialized form is not "an error", per se...

Think of it this way:

if you wanted to *de*serialize a stream and get the empty object you tried to serialize, an empty stream would suffice (ie, the "new" of the object would do the same thing) but if there's any data set on the object, now you need to actually save/load stuff

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

Now produces a byte array of 0x08, 0x01

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM