创建一个对象并添加一个List

本文关键字:List 一个 string 一个对象 添加 创建 | 更新日期: 2023-09-27 18:01:36

我有一个类Category,它有:

public int id { get; set; }
public string catName { get; set; }
public List<string> subCat { get; set; }

我想创建一个这样的列表:

List<Category> list = new List<Category>();
Category cat = new Category(){ 1 ,"Text", new List<string>(){"one", "two", "three"}};
list.Add(cat);

我得到了红色的错误标记,错误信息如下:

不能用集合初始化器初始化类型'Category',因为它没有实现'System.Collection.IEnumerable'

创建一个对象并添加一个List<string>

当你初始化它时,它会认为你在尝试实现一个列表。请执行以下操作:

var category = new Category
{
    id = 1,
    catName = "Text",
    subCat = new List<string>(){"one", "two", "three"}
};

有两种可能实现此目的。基本上你的思维方式是正确的,但你必须稍微改变一下。一种方法是让构造函数带有参数,这样当你创建该类的实例时,它就会用你的参数生成。

 List<Category> list = new List<Category>();  
 Category cat = new Category( 1 ,"Text", new List<string>(){"one", "two","three" });  
 list.Add(cat);  

和作为构造函数

public Category(int  _id, string _name, List<string> _list){  
 id = _id;  
 catName = _name;  
  subCat = _list;
}  

向类中添加getter和setter方法。创建一个对象,然后设置变量

 List<Category> list = new List<Category>();  
 Category cat = new Category();  
 cat.id =  1;  
 cat.catName = "Text";  
 cat.subCat = new List<string>(){"one", "two","three" };  
 list.Add(cat);

创建对象并赋值

Category cat = new Category();
cat.id = 1,
cat.catName = "Text",
cat.subCat = new List<string>(){"one", "two", "three"};
list.Add(cat);

使用普通构造函数执行该任务如何?例如:

public Category(int id, String catName, List<String> subCat){
this.id = id;
this.catName = catName;
this.subCat = subCat;
}

在您的Category类中使用此方法,并通过简单调用

来访问构造函数:
List<Category> list = new List<Category>();
Category cat = new Category(1, "Text", new List<String>(){"one", "two", "three"});

希望对你有帮助;)

相关文章: