继承自List< T>的对象 [英] Serializing object that inherits from List<T>

查看:52
本文介绍了继承自List< T>的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试序列化此集合时,name属性未序列化.

When I try to serialize this collection, the name property is not serialized.

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< t> 继承),并在其中定义字符串 Name 属性和 List< B_Button>时,bc = new List< B_Button>(); 属性,我得到了正确的结果.

Only if I create a new class (without List<t> inheritance), and define there string Name property and List<B_Button> bc = new List<B_Button>(); property I get the right result.

推荐答案

在许多序列化程序(实际上是数据绑定)中,对象是 实体(不包括)列表;通常不支持在列表上具有 属性.我将重构为封装列表:

In many serializers (and data-binding, in fact), an object is either an entity or (exclusive) a list; having properties on a list is not commonly supported. I would refactor to encapsulate the list:

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数组语法不允许任何额外的属性两者.

Also; how would you plan on representing that in JSON? IIRC the JSON array syntax doesn't allow for extra properties either.

这篇关于继承自List&lt; T&gt;的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆