gpt4 book ai didi

c# - 反序列化列表

转载 作者:行者123 更新时间:2023-11-30 16:25:19 25 4
gpt4 key购买 nike

我在反序列化时收到这个错误:

无效的线型;这通常意味着您在没有截断或设置长度的情况下覆盖了文件;见Using Protobuf-net, I suddenly got an exception about an unknown wire-type

那只提到文件截断,但我正在创建一个新文件

 Stopwatch sw = new Stopwatch();
List<SomeClass> items = CreateSomeClass();
sw.Start();
using (var file = File.Create(fileName))
{
var model = CreateModel();
model.Serialize(file, items);
file.SetLength(file.Position);
}
sw.Stop();
logger.Debug("Saving/serialization to {0} took {1} m/s", fileName, sw.ElapsedMilliseconds);
sw.Reset();
logger.Debug("Starting deserialzation...");
sw.Start();
using (var returnStream = new FileStream(fileName, FileMode.Open))
{
var model = CreateModel();
var deserialized = model.Deserialize(returnStream, null, typeof(SomeClass));
}
logger.Debug("Retrieving/deserialization of {0} took {1} m/s", fileName, sw.ElapsedMilliseconds);

public static TypeModel CreateModel()
{
RuntimeTypeModel model = TypeModel.Create();

model.Add(typeof(SomeClass), false)
.Add(1, "SomeClassId")
.Add(2, "FEnum")
.Add(3, "AEnum")
.Add(4, "Thing")
.Add(5, "FirstAmount")
.Add(6, "SecondAmount")
.Add(7, "SomeDate");
TypeModel compiled = model.Compile();

return compiled;
}

public enum FirstEnum
{
First = 0,
Second,
Third
}
public enum AnotherEnum
{
AE1 = 0,
AE2,
AE3
}
[Serializable()]
public class SomeClass
{
public int SomeClassId { get; set; }
public FirstEnum FEnum { get; set; }
public AnotherEnum AEnum { get; set; }
string thing;
public string Thing
{
get{return thing;}
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException("Thing");

thing = value;
}
}
public decimal FirstAmount { get; set; }
public decimal SecondAmount { get; set; }
public decimal ThirdAmount { get { return FirstAmount - SecondAmount; } }
public DateTime? SomeDate { get; set; }
}

我是 Protobuf-net 的新手,有什么明显的错误/遗漏吗?

最佳答案

您正在将其序列化为列表,并将其反序列化为单个项目。这是个问题。要么使用 DeserializeItems,要么:而不是

typeof(SomeClass)

通过

typeof(List<SomeClass>)

DeserializeItems 可能稍微快一些(出于各种原因,当使用列表类型作为操作数调用 Deserialize 时它必须做额外的工作)。

关于c# - 反序列化列表<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10032612/

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