简体   繁体   English

如何使用protobuf .NET序列化接口类型的成员?

[英]How to serialize interface-typed members with protobuf .NET?

The following test fails with this error: 以下测试失败并显示以下错误:

"System.InvalidOperationException : No suitable Default IB encoding found." “System.InvalidOperationException:找不到合适的默认IB编码。”

[ProtoContract]
public class A
{
    [ProtoMember(1)]
    public IB B { get; set; }
}

public interface IB
{
}

[ProtoContract]
public class B : IB
{
    [ProtoMember(1)]
    public int SomeProperty { get; set; }
}

[TestFixture]
public class TestFixture
{
    [Test]
    public void Test()
    {
        var a = new A {B = new B()};
        using (var m = new MemoryStream())
        {
            Serializer.Serialize(m, a);
        }
    }
}

I'm using this implementation of Protobuf.net : 我正在使用Protobuf.net的这个实现:

http://code.google.com/p/protobuf-net/ http://code.google.com/p/protobuf-net/

Did I miss something? 我错过了什么? thanks you very much. 非常感谢你。

That is a common feature of contract-based serializers, including XmlSerializer , etc (ie those that don't include type metadata for every object). 这是基于合同的序列化程序的常见功能,包括XmlSerializer等(即那些不包含每个对象的类型元数据的序列化程序)。

There are a few things that make this tricky: 有一些事情使这个棘手:

  • during deserialization, what type would it create for AB ? 在反序列化期间,它会为AB创建什么类型?
  • during serialization, the "what is the current object" bears little relationship to the contract 在序列化过程中,“当前对象是什么”与合同关系不大
    • in particular it gets very messy if the type implements multiple interfaces 特别是如果类型实现多个接口,它会变得非常混乱

This is a scenario I want to get something working for in "v2" though (but maybe not quite for release); 这是一个我希望在“v2”中获得某些工作的场景(但可能并不完全适用于发布); I'm thinking: 我在想:

  • either AB must be non-null to start with (ie A decides the type of AB ), or a default implementation must be specified somewhere 要么AB必须是非空的(即A决定AB的类型),或者必须在某处指定默认实现
  • interface-based is mutually exclusive vs. inheritance; 基于接口是互斥与继承; when using interfaces there can be no inheritance support 使用接口时,没有继承支持
  • all interface usage would be via properties, never fields (obviously) 所有接口用法都是通过属性,从不使用字段(显然)

Alternatively, and perhaps more suited to the scenario presented, we could use something like [ProtoInclude] to indicate the concrete types. 或者,也许更适合所呈现的场景,我们可以使用[ProtoInclude]类的东西来表示具体类型。

But within those limits I think something is possible. 但在这些限度内,我认为有可能。 But not today. 但不是今天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM