3 回答
TA貢獻1827條經驗 獲得超8個贊
將ChoiceList被初始化為null類時C1被創建。(事實上,每個類字段,包括隱藏的屬性支持字段,都被初始化為其默認值。)您必須顯式創建列表對象。
您可以在類構造函數中這樣做
public class C1
{
...
public List<StatusChoices> ChoiceList { get; set; }
public C1() // Constructor. Is run when a new C1 object is created with `new`.
{
ChoiceList = new List<StatusChoices>();
}
...
}
創建后,此列表為空。您必須向其中添加元素:
public string FillList(string v1, int v2, bool v3){
ChoiceList.Add(new StatusChoices{ val1 = v1, val2 = v2, val3 = v3 });
return v1;
}
請注意,您還必須創建一個StatusChoices對象。您可以將類視為可用于創建對象的模板。
將對象添加到列表后,可以通過枚舉訪問它們
foreach (StatusChoices sc in ChoiceList) {
Console.WriteLine($"val 1 = {sc.val1}, val 2 = {sc.val2}, val 3 = {sc.val3}")
}
或通過索引
StatusChoices first = ChoiceList[0];
StatusChoices second = ChoiceList[1];
string v1_of_first = first.val1;
string v1_of_second = second.val1;
您還可以直接訪問元素的屬性
string v1_of_first = ChoiceList[0].val1;
string v1_of_second = ChoiceList[1].val1;
如果你有一個對象C1 c1 = new C1();,你可以寫
string v = c1.ChoiceList[0].val1;
你甚至可以構造一個C1對象列表
var mainList = new List<C1>(); // The var-keyword lets C# infer the type.
// This saves you from writing List<C1> again.
mainList.Add(new C1());
mainList.Add(new C1());
mainList.Add(new C1());
mainList[0].FillList("a", 12, true);
mainList[0].FillList("b", 33, false);
mainList[1].FillList("x", 77, true);
...
string v = mainList[1].ChoiceList[2].val1;
我曾經ChoiceList.Add(new StatusChoices{ val1 = v1, val2 = v2, val3 = v3 });在列表中添加一個新元素。這是一個簡短的版本
StatusChoices sc = new StatusChoices();
sc.val1 = v1;
sc.val2 = v2;
sc.val3 = v3;
ChoiceList.Add(sc);
簡短版本使用對象初始值設定項{ val1 = v1, ... }。
TA貢獻1876條經驗 獲得超6個贊
像這樣的東西
public string FillList(string v1, int v2, bool v3){
this.ChoiceList = new List<StatusChoices> {
new StatusChoices { val1 = v1, val2 = v2, val3 = v3, } };
return this.ChoiceList[0].val1;
}
TA貢獻1770條經驗 獲得超3個贊
只需創建 StatusChoices 類的一個實例,對其進行初始化并將其添加到列表中。
(我添加了列表的延遲初始化)
public class C1{
public string p1 {get; set; }
public string p2 {get; set; }
public List<StatusChoices> ChoiceList { get; set; }
...
public string FillList(string v1, int v2, bool v3){
if(ChoiceList == null)
{
this.ChoiceList = new List<StatusChoices>();
}
var newItem = new StatusChoices {val1 = v1, val2 = v2, val3 = v3};
this.ChoiceList.Add(newItem);
return newItem.val1;
}
}
- 3 回答
- 0 關注
- 238 瀏覽
添加回答
舉報
