gpt4 book ai didi

c# - 使用多态性和 Protobuf-net 进行序列化和反序列化

转载 作者:太空狗 更新时间:2023-10-30 00:20:01 25 4
gpt4 key购买 nike

我正在尝试使用 protobuf-net序列化对象。我不确定我尝试用继承做的事情是否受支持,但我想我会检查一下是否受支持,或者我是否只是做错了什么。

本质上,我试图序列化一些子类,然后将其反序列化,但只使用基类引用。演示:

using UnityEngine;
using System.Collections;
using ProtoBuf;

public class main : MonoBehaviour
{
// If I don't put "SkipConstructor = true" I get
// ProtoException: No parameterless constructor found for Parent
// Ideally, I wouldn't have to put "SkipConstructor = true" but I can if necessary
[ProtoContract(SkipConstructor = true)]
[ProtoInclude(1, typeof(Child))]
abstract class Parent
{
[ProtoMember(2)]
public float FloatValue
{
get;
set;
}

public virtual void Print()
{
UnityEngine.Debug.Log("Parent: " + FloatValue);
}
}

[ProtoContract]
class Child : Parent
{
public Child()
{
FloatValue = 2.5f;
IntValue = 13;
}

[ProtoMember(3)]
public int IntValue
{
get;
set;
}

public override void Print()
{
UnityEngine.Debug.Log("Child: " + FloatValue + ", " + IntValue);
}
}

void Start()
{
Child child = new Child();
child.FloatValue = 3.14f;
child.IntValue = 42;

System.IO.MemoryStream ms = new System.IO.MemoryStream();

// I don't *have* to do this, I can, if needed, just use child directly.
// But it would be cool if I could do it from an abstract reference
Parent abstractReference = child;

ProtoBuf.Serializer.Serialize(ms, abstractReference);

ProtoBuf.Serializer.Deserialize<Parent>(ms).Print();
}
}

这个输出:

Parent: 0

我希望它输出的是:

Child: 3.14 42

这可能吗?如果是这样,我做错了什么?我在 SO 上阅读了关于继承和 protobuf-net 的各种问题,它们与这个例子都有点不同(据我所知)。

最佳答案

你会踢自己的。代码很好,除了一件事 - 你忘了倒回流:

ProtoBuf.Serializer.Serialize(ms, abstractReference);
ms.Position = 0; // <========= add this
ProtoBuf.Serializer.Deserialize<Parent>(ms).Print();

事实上,Deserialize 正在读取 0 个字节(因为它在末尾),因此试图创建父类型。就 protobuf 规范而言,空流是完全有效的 - 它仅表示没有任何有趣值的对象。

关于c# - 使用多态性和 Protobuf-net 进行序列化和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14949363/

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