Joh*_*nes 98 c# collections initialization list
我正在写我的测试代码,我不想写写:
List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
Run Code Online (Sandbox Code Playgroud)
我很想写
List<string> nameslist = new List<string>({"one", "two", "three"});
Run Code Online (Sandbox Code Playgroud)
但是{"one","two","three"}不是"IEnumerable string Collection".如何使用IEnumerable字符串Collection在一行中初始化它?
Mat*_*ott 156
var list = new List<string> { "One", "Two", "Three" };
Run Code Online (Sandbox Code Playgroud)
本质上语法是:
new List<Type> { Instance1, Instance2, Instance3 };
Run Code Online (Sandbox Code Playgroud)
这是由编译器翻译的
List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");
Run Code Online (Sandbox Code Playgroud)
Adr*_*der 16
将代码更改为
List<string> nameslist = new List<string> {"one", "two", "three"};
Run Code Online (Sandbox Code Playgroud)
要么
List<string> nameslist = new List<string>(new[] {"one", "two", "three"});
Run Code Online (Sandbox Code Playgroud)
为想要使用 POCO 初始化列表的人们发布此答案,因为这是搜索中弹出的第一件事,但所有答案仅适用于字符串类型列表。
您可以通过两种方式执行此操作,一种是通过 setter 赋值直接设置属性,或者通过创建一个接受参数并设置属性的构造函数来更简洁。
class MObject {
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };
Run Code Online (Sandbox Code Playgroud)
或者通过参数化构造函数
class MObject {
public MObject(int code, string org)
{
Code = code;
Org = org;
}
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};
Run Code Online (Sandbox Code Playgroud)
只是丢失括号:
var nameslist = new List<string> { "one", "two", "three" };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124563 次 |
| 最近记录: |