首页 > 解决方案 > 手动填写 C# 数据类型集合列表

问题描述

我正在研究一个 C# 示例来学习列表以及如何初始化它们。所以我有一个具有一些属性的类:

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)
    {
        // How can I fill this.ChoiceList?

        this.ChoiceList.val1 = v1; //Is this possible?

        return this.ChoiceList.val1;
    }
}

public class StatusChoices
{
    public string val1 { get; set; }
    public int val2    { get; set; }
    public bool val3   { get; set; }
}

这可能很容易,但到目前为止我无法实现。如何将一些值“手动”添加到列表中?

标签: c#listproperties

解决方案


在创建类时ChoiceList初始化。(事实上​​,每个类字段,包括隐藏的属性支持字段,都被初始化为其默认值。)您必须显式地创建列表对象。nullC1

您可以在类构造函数中这样做

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, ... }


推荐阅读