gpt4 book ai didi

c# - Protobuf-net 序列化问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:01 25 4
gpt4 key购买 nike

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

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 有点奇怪……零长度序列化形式本身并不是“错误”……

这样想:

如果你想*反*序列化一个流并得到你试图序列化的空对象,一个空流就足够了(即,对象的"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

关于c# - Protobuf-net 序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com