【问题标题】:Protobuf-net - How to add same field in inherited class with backward version compatibilityProtobuf-net - 如何在具有向后版本兼容性的继承类中添加相同的字段
【发布时间】:2022-09-27 17:14:47
【问题描述】:

假设我有以下类结构:

基类:

[ProtoContract]
[ProtoInclude(10, typeof(Store))]
[ProtoInclude(11, typeof(House))]
public abstract class Address
{
   [ProtoMember(1)] Id ;
   [ProtoMember(2)] string Country;
   [ProtoMember(3)] string Pincode;
}

儿童班 1:

[ProtoContract]
public class Store: Address
{
   [ProtoMember(1)] int StoreUniqueid;
   [ProtoMember(2)] string StoreUniqueValue;
   [ProtoMember(3)] string Pincode;
}

幼儿班 2:

[ProtoContract]
public class House : Address
{
   [ProtoMember(1)] int HouseArea;
}

现在,我需要将 Store 类的“Pincode”属性引入 House 类。

解决此问题以保持向后兼容性的理想方法应该是什么?

选项 1:将 Store 类的 Pincode 属性移动到 Address(基)类。但是,这可能会产生向后兼容性问题,因为我们必须从 Store 类中删除 Pincode 属性。

选项 2:在 House 类中添加另一个相同的属性(Pincode),如下所示(不确定这是否是正确的方法。)

[ProtoContract]
public class House: Address
{
   [ProtoMember(1)] int HouseArea;
   [ProtoMember(2)] string Pincode;
}

    标签: .net protobuf-net


    【解决方案1】:

    字段由继承级别限定;在基本级别添加附加字段不会在派生级别引起任何冲突。如果您的意图是仍然能够反序列化旧格式,那么您可以将派生的Pincode 替换为:

        [ProtoMember(3)]
        private string PincodeDeserializeCompat // only for deserialization
        {
            get => Pincode;
            set => Pincode = value;
        }
        private bool ShouldSerializePincodeDeserializeCompat() => false;
    

    ShouldSerialize* 方法禁用该成员的序列化;你可以尝试使用:

        [ProtoMember(3)]
        private string PincodeDeserializeCompat // only for deserialization
        {
            get => null; // disable serialize
            set => Pincode = value;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多