【问题标题】:How does deriving work in protobuf-net?protobuf-net 中的派生是如何工作的?
【发布时间】:2014-10-06 10:39:59
【问题描述】:

就像我在 C# 中所做的那样:

class DerivedClass : BaseClass {}

有没有办法用原始文件中的消息重新创建这种行为? 这样DerivedClass 的类型为BaseClass 并且可以继承其属性。

我尝试extend 我的基本消息,但这会产生不同的结果。

【问题讨论】:

    标签: protobuf-net derived-types


    【解决方案1】:

    如果我们假设这是:

    [ProtoContract]
    [ProtoInclude(7, typeof(DerivedClass))]
    public class BaseClass {}
    
    [ProtoContract]
    public class DerivedClass : BaseClass {}
    

    那么我们可以使用:

    string proto = Serializer.GetProto<BaseClass>();
    

    看看 protobuf-net 是如何解释它的:

    message BaseClass {
       // the following represent sub-types; at most 1 should have a value
       optional DerivedClass DerivedClass = 7;
    }
    message DerivedClass {
    }
    

    这实际上可以很好地映射到新的oneof - 简单地说,GetProto 尚未更新为使用新语法(但它不会影响输出)。但以下也是等价的:

    message BaseClass {
        oneof subtypes {
            // the following represent sub-types; at most 1 should have a value
            DerivedClass DerivedClass = 7;
            AnotherDerivedClass AnotherDerivedClass = 8;
            AndOneMoreForLuck AndOneMoreForLuck = 9;
        }
    }
    message DerivedClass {
    }
    message AnotherDerivedClass {
    }
    message AndOneMoreForLuck {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      相关资源
      最近更新 更多