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

标签 c# serialization protobuf-net protocol-buffers

使用 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/

相关文章:

c# - 为什么 nservicebus 忽略我的订阅消息?

c# - Protobuf-net 不序列化泛型类型继承自泛型类型

c# - 使用由 google 的 protobuf 序列化的 protobuf-net 反序列化数据时出现问题

c# - C# 丢弃有任何性能优势吗?

c# - 如何用表达式参数实现方法c#

c# - 过滤器函数的奇数签名

c++ - 使用 Boost,如何在类层次结构更改后反序列化 C++ 类

java - JSON - 无法使用 Jackson 序列化对象内的 JSONObject

java - 如何在 Java 中优雅地序列化和反序列化 OpenCV YAML 校准数据?

c# - 动态对象序列化