【问题标题】:Can't serialize property when its parent inherits from IList<>当其父级继承自 IList<> 时无法序列化属性
【发布时间】:2013-04-29 01:46:46
【问题描述】:

我对继承自 IList&lt;string&gt;Family 类使用以下数据结构:

public class Family : IList<string>
{
    public string LastName { get; set; }

   //IList<string> members
              .                .
              .

   //IList<string> members
}

我创建了自己的RuntimeTypeModel 并像这里一样添加Family 类型:

RuntimeTypeModel myModel = RuntimeTypeModel.Create();
MetaType familyMetaType = myModel.Add(typeof(Family), true);
familyMetaType.AddField(1, "LastName");
familyMetaType.AddField(2, "Item").IsPacked = true; ;
familyMetaType.CompileInPlace();
myModel.Compile();

然后我创建一个Family 对象并对其进行序列化:

Family family = new Family();
family.LastName = "Sawan";
family.Add("Amer");

using (FileStream fs = new FileStream("Dump.proto", FileMode.Create))
    myModel.Serialize(fs, family);

但是当我反序列化它时,我只得到 string 集合的成员,而不是 LastName 值。

我应该为我的RuntimeTypeModel 设置什么配置,以使其序列化其他对象,如本例中的LastName

【问题讨论】:

    标签: serialization protobuf-net


    【解决方案1】:

    XmlSerializer 和其他几个一样,protobuf-net 在列表和实体之间画了一条硬线。就 protobuf-net 而言,不能两者兼而有之。如果您不希望它选择“列表”,您可以在[ProtoContract] 上使用IgnoreListHandling (IIRC) - 但这显然不会序列化列表中的项目。通常最好是一个名字并且列表的对象:

    [ProtoContract]
    public class Family
    {
        [ProtoMember(1)] public string LastName { get; set; }
        [ProtoMember(2)] public IList<string> Items {get{return items;}}
    
        private readonly IList<string> items = new List<string>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 2012-11-28
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多