1

我想展平用于定义 protobuf-net 合同的类型层次结构,我们目前在该合同中具有以下内容:

[ProtoContract]
public class SubClass : BaseClass
{
   [ProtoMember(1)]
   public string Prop1 { get; set; }
}

[ProtoContract]
[ProtoInclude(1, typeof(SubClass))]
public class BaseClass
{
   [ProtoMember(100)]
   public string Prop2 { get; set; }
}

然后将其重构为

[ProtoContract]
public class SubClass
{
   [ProtoMember(1)]
   public string Prop1 { get; set; }

   [ProtoMember(100)]
   public string Prop2 { get; set; }
}

这样在重构之前序列化的实例被成功反序列化。这是否可以简单地通过选择正确的索引或者我需要做更多的事情?

4

1 回答 1

1

在底层,protobuf-net 中的继承以一种基本上是多级操作的方式实现。对其进行建模并非易事,坦率地说,使用自动映射器之类的东西可能更容易,即将数据加载到模型中;将其映射到模型;序列化新模型。请注意,这是一项重大更改,之后数据将不兼容。但是,如果您可以忍受一点丑陋,则可以在一个模型中执行此操作(尽管请注意,我必须提供不同的字段编号才能使其起作用):

[ProtoContract]
public class NewClass
{
    [ProtoMember(2)]
    public string Prop1 { get; set; 

    [ProtoMember(100)]
    public string Prop2 { get; set; }

    [ProtoMember(1)] // this 1 is from ProtoMember
    private Shim ShimForSerialization { get { return new Shim(this); } }

    // this disables the shim during serialiation; only Prop1 and Prop2 will
    // be written
    public bool ShouldSerializeShimForSerialization() { return false; }

    [ProtoContract]
    private class Shim {
        private readonly NewClass parent;
        public Shim(NewClass parent) {
            this.parent = parent;
        }
        [ProtoMember(1)]
        public string Prop1 {
            get { return parent.Prop1;}
            set { parent.Prop1 = value;}
        }

    }
}
于 2013-01-11T13:58:28.200 回答