Skip to main content
 首页 » 编程设计

c#之使用 protobuf-net,序列化实现接口(interface)的派生类型的正确方法是什么

2024年02月20日15jpfss

我意识到这里有类似的问题,但没有一个像我需要的那样直接地问这个问题,可能是因为我缺乏 protobuf 经验。我正在为 enyim 的缓存客户端进行代码转换,并且无法弄清楚如何创建一个既派生又实现接口(interface)正确反/序列化的类。

像这样的例子

public class BaseClass 
{ 
} 
 
public interface ISomeRules 
{ 
} 
 
public class DerivedClass : BaseClass, ISomeRules 
{ 
} 
 
public class ThirdClass 
{ 
    ISomeRules ruleUser; 
} 

我想做这样的事情,因为我一般到处都使用属性

[ProtoContract 
,ProtoInclude(101,typeof(DerivedClass)) 
] 
public class BaseClass 
{ 
} 
 
[ProtoContract 
,ProtoInclude(102,typeof(DerivedClass)) 
] 
public interface ISomeRules 
{ 
} 
 
[ProtoContract] 
public class DerivedClass : BaseClass, ISomeRules 
{ 
} 
 
[ProtoContract] 
public class ThirdClass 
{ 
    [ProtoMember(1)] 
    ISomeRules ruleUser; 
} 

但它无法静默缓存。如果像某些人建议的那样,我从 ISomeRules 中删除了 ProtoContract 属性,反序列化就会失败。

使用 protobuf-net 是否可行?这样做的正确方法是什么?我应该改用 TypeModel(我不掌握它,但简单的测试表明它有同样的问题)吗?还是 TypeModel 和属性的组合?

请您参考如下方法:

protobuf-net 中的接口(interface)支持适用于有限的场景,您基本上是在使用基于接口(interface)的模型,尤其是嵌套成员。例如:

[ProtoContract] 
public class Foo { 
    [ProtoMember(1)] 
    public IBar Bar {get;set;} 
} 

在上面,我们希望能够序列化Bar,但我们可能对此了解不多。事实上,如果 Foo 保证从 Bar 返回一个非空值,protobuf-net 甚至不需要知道任何关于具体类型等的信息——它可以直接去提前填充给定的对象。

在您的示例中,根对象无疑是 BaseClass。我建议 ISomeRules 是附属的,并且不需要在模型中提及根本。但是,如果您想要填充仅通过ISomeRules公开的成员,那么您可以尝试(未测试):

[ProtoMember(n)] 
private ISomeRules Rules { get { return this; } } 

然后这将公开 ISomeRules 信息,但将其伪装成子对象。至少,值得一试;