gpt4 book ai didi

c# - 使用 protobuf-net 反序列化后的不一致

转载 作者:行者123 更新时间:2023-11-30 15:31:51 30 4
gpt4 key购买 nike

使用 protobuf-net 反序列化后,我遇到了不一致的问题。

我想要序列化/反序列化的类如下所示:

[ProtoContract]
public class TSS
{
[ProtoMember(1, AsReference = true)]
public EventManager eventManager { get; private set; }

[ProtoMember(2)]
public DateTime referenceDateTime { get; private set; }

[ProtoMember(3)]
public Mode mode;
}

在 EventManager 类中,它看起来像:

[ProtoContract]
public class EventManager
{
[ProtoMember(1)]
public InputQueue inputQueue = new InputQueue();
[ProtoMember(2)]
public InputQueue InputQueue
{
get { return this.inputQueue; }
set { this.inputQueue = value; }
}
[ProtoMember(7, AsReference = true)]
public TSS tss;
}

EventManager类中的tss是TSS对象的引用,TSS类中的eventManager是EventManager对象的引用。这就是我将 AsReference = true 放在那里的原因(这是正确的方法吗?)

我像这样进行序列化:

public void StateSaving(int time, TSS tss)
{
Stream memoryStream = new MemoryStream();
Serializer.Serialize(memoryStream, tss);
states.Add(time, memoryStream);
}

并像这样进行反序列化:

public void Deserialize(int time, ref TSS tss)
{
Stream memoryStream = states[time];
memoryStream.Position = 0;
tss = Serializer.Deserialize<TSS>(memoryStream);
}

问题是,每当我进行反序列化时,EventManager 中的 inputQueue 等数据结构都会填充 NULL 值,而不是此时的实际值。我是protobuf-net的新手,有错误请指出(我相信有很多)。

提前致谢!

最佳答案

(来自评论)

I have located the problem, basically there's a list that needs to be deserialized. And this list is a list of events, in which the constructors of the events have parameters, and when it tries to deserialize, the program will run the parameterless constructors (I manually added these constructors in order to eliminate the exceptions) instead of the right ones (with parameters). I know this is how serialization/deserialization work, but is there a way I can serialize and deserialize this list correctly?

啊,确实如此。对象构建有多种方法:

  • 使用无参构造函数
  • 寻找匹配所有已定义成员的构造函数
  • 完全跳过构造函数
  • 使用自定义对象工厂
  • 使用代理对象和自定义转换

XmlSerializer之类的东西使用第一个; DataContractSerializerBinaryFormatter 使用第三个;好消息是 protobuf-net 支持所有 5。我建议,在您的情况下,最好的选择是对这种类型使用第三个选项,您可以通过以下方式完成:

[ProtoContract(SkipConstructor=true)]

关于c# - 使用 protobuf-net 反序列化后的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20059333/

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