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

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

当前回答

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

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

其他回答

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

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

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

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

List<string> optionList = new List<string>
            { "AdditionalCardPersonAdressType", /* rest of elements */ };
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

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

例子:

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

你就会这么做。

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

不要忘记添加

使用System.Collections.Generic;