为什么以下 protobuf-net 使用是非法的?

发布于 2024-11-09 15:37:30 字数 1017 浏览 3 评论 0原文

  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);
      }
    }
  }

当我尝试向 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)
  InnerException: 
  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)
  InnerException: 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖哒 2024-11-16 15:37:30

大约 2 分钟前,这是非法的,因为接口不支持已知类型。

现在,这种用法是非法的,因为它IYObject.X无法安全地序列化,因为它没有setter。但是,只要我们将自己限制为可以合理序列化的接口成员或具体类型的成员,现在就已提交。使用属性或类型模型。 请在此处查看现在可用的方案(通过代码或下一次公开发布)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文