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

时间:2012-05-28 05:28:58

标签: c# protobuf-net

我认为我的问题与这个问题非常相似: Protobuf-net creating typemodel with interface and abstract baseclass 但是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

1 个答案:

答案 0 :(得分:1)

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

因为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]可能都不重要。我发现将它们全部放在一起似乎也有效。