如何初始化(使用c#初始化器)字符串列表?我已经尝试了下面的例子,但它不工作。
List<string> optionList = new List<string>
{
"AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
如何初始化(使用c#初始化器)字符串列表?我已经尝试了下面的例子,但它不工作。
List<string> optionList = new List<string>
{
"AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
当前回答
如果您使用的是c# 9.0及更高版本,则可以使用新特性目标类型的new表达式Link
例子:
List<string> stringList = new(){"item1","item2", "item3"} ;
其他回答
var animals = new List<string> { "bird", "dog" };
List<string> animals= new List<string> { "bird", "dog" };
以上两种是最短的方式,请参见https://www.dotnetperls.com/list
这就是初始化的方式,如果你想让它更动态,你也可以使用List.Add()。
List<string> optionList = new List<string> {"AdditionalCardPersonAdressType"};
optionList.Add("AutomaticRaiseCreditLimit");
optionList.Add("CardDeliveryTimeWeekDay");
通过这种方式,如果从IO中获取值,可以将其添加到动态分配的列表中。
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });
你就会这么做。
List <string> list1 = new List <string>();
不要忘记添加
使用System.Collections.Generic;
您还没有真正提出问题,但代码应该提出问题
List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"};
例如,在列表后面没有尾随()。