【问题标题】:Serializing object that inherits from List<T>序列化从 List<T> 继承的对象
【发布时间】:2023-03-30 20:53:01
【问题描述】:

当我尝试序列化这个集合时,name 属性没有被序列化。

public class BCollection<T> : List<T> where T : B_Button
{       
   public string Name { get; set; }
}


BCollection<BB_Button> bc = new BCollection<B_Button>();

bc.Name = "Name";// Not Serialized!

bc.Add(new BB_Button { ID = "id1", Text = "sometext" });

JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(bc);

只有当我创建一个新类(没有List&lt;t&gt; 继承),并在那里定义字符串Name 属性和List&lt;B_Button&gt; bc = new List&lt;B_Button&gt;(); 属性时,我才能得到正确的结果。

【问题讨论】:

    标签: c# serialization


    【解决方案1】:

    在许多序列化程序(实际上是数据绑定)中,对象是要么实体(排他的)列表;通常不支持在列表具有属性。我会重构 encapsulate 列表:

    public class Foo<T> {
        public string Name {get;set;}
        private readonly List<T> items = new List<T>();
        public List<T> Items { get { return items; } }
    }
    

    还有;你打算如何用 JSON 来表示它? IIRC JSON 数组语法不允许额外的属性 either.

    【讨论】:

    • 我只是用它来将数据传递给客户端(脚本控件),在那里我对其进行反序列化并检索数据。
    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    相关资源
    最近更新 更多