c# - 手动填写 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; }
}
这可能很容易,但到目前为止我无法实现。如何将一些值“手动”添加到列表中?
解决方案
在创建类时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, ... }
。
推荐阅读
- azure - [警告]找不到键的 loc 字符串:CorrelationIdForARM
- python-3.x - 在列出每个项目后将项目添加到带有输入的空列表
- c# - 是否可以捕获或隐藏非托管异常窗口?
- python - 从接口的 IP 和网络掩码获取网络 IP
- python-3.x - 在熊猫数据框中仅显示重复值序列中的第一个实例的更好方法?
- drupal - Drupal:从 submitForm() 中的控制器调用函数时出现“错误:找不到类”
- javascript - 如何使用 Promise 设置变量的值,然后使用 Express 发布到 db?
- linux - 如何读取套接字接收到的 TCP 段数
- python - 如何在 Python 中求解具有两台服务器的马尔可夫链的大概率矩阵?
- c++ - 段错误、动态数组和函数