gpt4 book ai didi

c# - 序列化继承自 List 的对象

转载 作者:太空狗 更新时间:2023-10-30 00:46:07 25 4
gpt4 key购买 nike

当我尝试序列化这个集合时,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<t> 继承),并在那里定义字符串 Name 时属性(property)和List<B_Button> bc = new List<B_Button>();属性我得到了正确的结果。

最佳答案

在许多序列化程序(以及数据绑定(bind),事实上)中,一个对象是或者一个实体或者(不包括)一个列表;通常不支持在列表中包含 属性。我会重构以封装列表:

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

关于c# - 序列化继承自 List<T> 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4105762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com