正如在https://docs.microsoft.com/de-de/visualstudio/code-quality/ca2227?view=vs-2019中所解释的,我有一个对象,其只读列表如下所示:
public class MyClass {
public int id { get; set; }
public List<string> stringList { get; } = new List<string>;
}但是如何通过向stringList添加数据来初始化MyClass呢
MyClass test = new MyClass(){
id = 1,
stringList = ???
}发布于 2020-06-16 20:39:47
您可以对collection initializers使用不太明显的语法
var x = new MyClass
{
id = 1,
stringList = {"as", "ddsd"} // will ADD "as", "ddsd" to stringList
};
Console.WriteLine(string.Join(", ", x.stringList)); // prints as, ddsd处理只读属性(直到init only properties and records发布C# 9之前)的常用方法是在构造函数中传递初始化值。
发布于 2020-06-16 20:39:58
您可以在构造函数中将stringList作为参数传递,并将属性分配给该参数:
public class MyClass {
public int id { get; set; }
public List<string> stringList { get; } = new List<string>();
public MyClass(List<string> stringList) {
this.stringList = stringList;
}
}https://stackoverflow.com/questions/62408635
复制相似问题