[英]create an object and add a List<string>
我有一個類別類別:
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'
任何幫助都會很有幫助。
順便說一下,你正在初始化它,它認為你正在嘗試實現一個列表。 請執行以下操作。
var category = new Category
{
id = 1,
catName = "Text",
subCat = new List<string>(){"one", "two", "three"}
};
有兩種可能性可以實現這一點。 基本上你的思維方式是正確的。 但你必須改變一下。 一種方法是使用Parameters創建構造函數,因此如果您創建此類的實例,則使用您的參數生成它。
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的對象並賦值
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"});
希望這可以幫助你;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.