gpt4 book ai didi

c# - 使用 protobuf-net 序列化具有接口(interface)类型成员的类

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:41 24 4
gpt4 key购买 nike

我无法使用 protobuf-net 序列化我的类,问题似乎是 protobuf-net 无法序列化接口(interface)。

interface MyInterface
{
string name;
}

[ProtoContract]
[ProtoInclude(1, typeof(MyClass1))]
[ProtoInclude(2, typeof(MyClass2))]
public abstract class ParentClass
{
[ProtoMember(1)]
List<MyInterface> elements;
}


[ProtoContract]
public class MyClass1 : ParentClass, MyInterface
{
[ProtoMember(1)]
int x;
}

[ProtoContract]
public class MyClass2 : MyInterface
{
[ProtoMember(1)]
string y;
}

我无法序列化 MyClass1 类型的任何对象,因为元素是一个接口(interface)列表,可以是 Mylass1 或 MyClass2。我收到一些编码未设置错误。

谁能告诉我如何解决这个问题。谢谢。

最佳答案

在当前的正式版本中,我不包括接口(interface)序列化支持。但是,我确实有一个补丁(来自另一个用户)似乎可以实现这一点。

我还没有将这个补丁应用到核心,只是因为我需要在添加更多功能之前先专注于完成“v2”(特别是因为该功能需要完全重新-为 v2 实现),但如果您愿意,我很乐意与您分享补丁。

或者:使用基类而不是接口(interface)。 受支持(通过 [ProtoInclude])- 然而,您的 MyClass1 已经有一个父类这一事实使事情变得有些复杂。


编辑:现在 v2 中支持此功能。显然,代码必须知道预期的具体实现 - 但现在可以将包含附加到接口(interface)(或可选地在普通 POCO 模型的代码中指定)。

关于c# - 使用 protobuf-net 序列化具有接口(interface)类型成员的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3783289/

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