如何停止使用 Protobuf-Net 继承,直接使用继承类?

Posted

技术标签:

【中文标题】如何停止使用 Protobuf-Net 继承,直接使用继承类?【英文标题】:How to stop using Protobuf-Net inheritance and use inherited classes directly? 【发布时间】:2017-05-04 14:47:50 【问题描述】:

我有一个继承自基类的继承设置类,我想单独(反)序列化(示例)

[ProtoContract]
[ProtoInclude(1, typeof(GlobalSettings))]
[ProtoInclude(2, typeof(UserSettings))]
public class BaseSettings



[ProtoContract]
public class GlobalSettings: BaseSettings

    [ProtoMember(1)]
    public string TempPath  get; set; 


[ProtoContract]
public class UserSettings: BaseSettings

    [ProtoMember(1)]
    public int UILanguage  get; set; 

唯一的问题是我不能承受丢失配置,如果 UserSettings 不再从 BaseSettings 继承并移动到另一个程序集以独立使用,(反)序列化仍然是可能的(有一些某种转换或没有)无法访问 GlobalSettings 类?

【问题讨论】:

【参考方案1】:

继承是序列化模型的基本组成部分,尤其是,如果您曾经谈论过Deserialize<BaseSettings>。如果你Deserialize<GlobalSettings>Deserialize<UserSettings>之类的事情,那么你也许可以删除[ProtoInclude]s,但随后问题就变成了宣布BaseSettings的成员进入子-类型。有办法做到这一点。

【讨论】:

我尝试使用只有一个属性 [ProtoMember(1)] UserSettings 的 [ProtoContract] 创建另一个基类,但它不起作用。仅使用 [ProtoInclude(1, typeof(UserSettings)] 创建一个虚拟基类效果很好。由于您没有提到它,我猜没有 ProtoContract 选项可以在不添加虚拟基类的情况下“伪造”继承。谢谢您的帮助。

以上是关于如何停止使用 Protobuf-Net 继承,直接使用继承类?的主要内容,如果未能解决你的问题,请参考以下文章

限制 protobuf-net 继承“树”

Protobuf-net.Grpc 服务契约继承

用于继承的 Protobuf-net .proto 文件生成

关于继承的 ProtoBuf-Net 的问题?

Protobuf-net 中的继承:ProtoInclude 和兼容性

不支持 Protobuf-NET IExtensible 继承的解决方法