如何初始化(使用c#初始化器)字符串列表?我已经尝试了下面的例子,但它不工作。

List<string> optionList = new List<string>
{
    "AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();

当前回答

var animals = new List<string> { "bird", "dog" };
List<string> animals= new List<string> { "bird", "dog" };

以上两种是最短的方式,请参见https://www.dotnetperls.com/list

其他回答

你就会这么做。

List <string> list1 = new List <string>();

不要忘记添加

使用System.Collections.Generic;

var animals = new List<string> { "bird", "dog" };
List<string> animals= new List<string> { "bird", "dog" };

以上两种是最短的方式,请参见https://www.dotnetperls.com/list

只需在最后删除()即可。

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };

您还没有真正提出问题,但代码应该提出问题

List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"}; 

例如,在列表后面没有尾随()。

如果您使用的是c# 9.0及更高版本,则可以使用新特性目标类型的new表达式Link

例子:

List<string> stringList = new(){"item1","item2", "item3"} ;