开发者

Why is the following protobuf-net usage illegal?

  public interface IYObject
  {
    string X { get; }
  }

  public class YObject : IYObject
  {
    public string X { get; set; }
  }

  public class D
  {
    public IYObject Y { get; set; }
  }

  class Program
  {
    static void Main()
    {
      var m = RuntimeTypeModel.Default;
      m.Add(typeof(D), true).Add("Y");
      m.Add(typeof(IYObject), false).AddSubType(1, typeof(YObject)).Add("X");
      var d = new D { Y = new YObject { X = "a" } };
      using (var ms = new MemoryStream())
      {
        Serializer.Serialize(ms, d);
        ms.Position = 0;
        var d2 = Serializer.Deserialize<D>(ms);
        Debug.Assert(d.Y.X == d2.Y.X);
      }
    }
  }

The code fails when I try to add a subtype to IYObject:

System.InvalidOperationException occurred
  Message=Sub-types can only be adedd to non-sealed classes
  Source=protobuf-net
  StackTrace:
       at ProtoBuf.Meta.MetaType.AddSubType(Int32 fieldNumber, Type derivedType)
  InnerExceptio开发者_Python百科n: 


Before about 2 minutes ago, it was illegal because known-types weren't supported against interfaces.

Now, that usage is illegal because it can't safely serialize IYObject.X because it has no setter. However, as long as we restrict ourselves to interfaces members that can be sensible serialized, or members on the concrete type, this is now committed. Using either attributes or the type model. See here for the scenarios that are now available (via either code, or the next public drop).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜