【问题标题】:Force protobuf-net to ignore IEnumerable/ICollection interfaces强制 protobuf-net 忽略 IEnumerable/ICollection 接口
【发布时间】:2012-01-11 20:25:20
【问题描述】:

如何让 v2 ​​的 protobuf-net 忽略我的类实现 ICollection、IEnumerable 等这一事实?

对于这种特殊情况,我只希望对标记为 [ProtoMember] 的字段进行序列化。


我目前正在从使用 protobuf-net v1 转换为使用 v2。我有一个特定的结构,现在由于更改而序列化不正确。它看起来像下面这样:

[ProtoContract]
public class FileTree : ICollection<FilePath>, IEnumerable<FilePath>, IEnumerable, INotifyCollectionChanged, INotifyPropertyChanged {

    private FileTreeNode _Root;

    [ProtoMember (1)]
    public FileTreeNode Root {
        get { return _Root; }
        set { _Root = value; }
    }
}

编写 FileTree 类是为了将“C:\happy.txt”“C:\history.txt”等文件路径折叠成更像

"C:\h"
└─── "appy.txt"
└─── "istory.txt"

该结构消除了路径字符串中的冗余。所以,我真的不希望 FileTree 类通过 IEnumerable 函数被序列化,因为它只是被存储为“C:\happy.txt”、“C:\history.txt”等。现在,在序列化中FileTree 对象的每个路径都被完整打印出来。


编辑:最后一件事我应该提到——我在 FileTree 中有一个 On_Deserialization 函数,它被标记为 [ProtoAfterDeserialization]。我在函数中设置了一个断点,但它没有被命中。这与这个类的序列化方式有关吗?

【问题讨论】:

  • 我不知道这是 v1 和 v2 之间的重大变化;或许细微的差别在于 v1 更多地寻找 IList&lt;T&gt;,或 IEnumerable&lt;T&gt; 公共 Add 的组合。

标签: c# wpf serialization .net-4.0 protobuf-net


【解决方案1】:
[ProtoContract(IgnoreListHandling = true)]
public class FileTree : ICollection<FilePath> ...
{ ... }

应该这样做。老实说,我认为我没有考虑过列表上的回调,因为它们的处理方式与实体非常不同,但是上面应该可以工作。如果没有,请告诉我。

来自智能感知文档:

获取或设置一个值,指示此类型不应被视为列表,即使它具有熟悉的类似列表的特征(可枚举、添加等)

【讨论】:

  • 谢谢!当回想起来答案如此明显时,很抱歉打扰您。我在所有错误的地方寻找答案。
  • @Amanduh 当你知道答案时,大多数事情都是显而易见的,但是 - 这是一个很好且有效的问题,幸运的是 一个方便的答案(它没有直到最近)
  • @MarcGravell 请注意,IgnoreListHandling 选项在complex scenarios 中可能无法按预期工作。
猜你喜欢
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多