protobuf-net是否支持多接口继承

本文关键字:接口 继承 支持 是否 protobuf-net | 更新日期: 2023-09-27 18:35:27

我认为我的问题与这个问题非常相似:Protobuf-net 创建具有接口和抽象基类的类型模型然而,Marc 在这里给出的解决方案本质上将抽象类和接口的多重继承减少到单个继承设计中。

对我来说的问题是,我实际上需要这样的多个接口继承:

interface ITestBase 
{
}
abstract class TestBase : ITestBase 
{
}
class TestTypeA : TestBase, ITestTypeA 
{
}
interface ITestTypeA 
{
}
class TestTypeB : TestBase, ITestTypeB 
{
}
interface ITestTypeB 
{
}

在这里,我不能通过让TestBase实现ITestTypeA或ITestTypeB(就像另一个问题的解决方案一样)来轻视这一点,因为具体的类TestTypeA应该同时实现ITestTypeA和ITestBase,而TestTypeB应该实现ITestTypeB和ITestBase。

我正在使用protobuf-net v2.0.0.480

protobuf-net是否支持多接口继承

我找到了这个可行的解决方案。不确定它是否被推荐,或者它是否会在运行时不知不觉中中断,但到目前为止它似乎适用于我的测试。

因为 protobuf-net 将接口视为序列化的具体类,所以它会遇到多个继承问题(这就是我对它的理解),所以我所做的只是从一个基类继承,并且不指定任何类之间的关系到它们的接口。

并创建一个可用于定义类层次结构的具体基类,如下所示。

[ProtoContract]
interface ITestBase 
{
}
[ProtoContract]
[ProtoInclude(1, typeof(TestTypeA))]
[ProtoInclude(2, typeof(TestTypeB))]
abstract class TestBase : ITestBase
{
}
[ProtoContract]
class TestTypeA : TestBase, ITestTypeA 
{
}
[ProtoContract]
interface ITestTypeA 
{
}
[ProtoContract]
class TestTypeB : TestBase, ITestTypeB 
{
}
[ProtoContract]
interface ITestTypeB 
{
}

实际上,接口前面的所有[ProtoContract]甚至可能无关紧要。我发现把它们一起拿出来似乎也有效。