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

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

当前回答

你就会这么做。

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

不要忘记添加

使用System.Collections.Generic;

其他回答

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

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

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

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

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

我已经看到了c#的内容标签,但如果有人可以使用Java(相同的搜索词引导这里):

List<String> mylist = Arrays.asList(new String[] {"element1", "element2", "element3" }.clone());
List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

你可能忽略了一些没有被提及的事情。我认为这可能是你遇到的问题,因为我怀疑你已经尝试删除尾随(),仍然得到一个错误。

首先,就像其他人在这里提到的,在你的例子中,你确实需要删除尾随();

但是,还要注意List<>在System.Collections.Generic命名空间中。

所以,你需要做以下两种选择之一: [下面的第一条可能是更可取的选择]

(1) 在你的代码顶部包含命名空间的使用: 使用System.Collections.Generic;

or

(2) 在声明中放入List的完全限定路径。

System.Collections.Generic.List optList=新的System.Collections.Generic.List {" AdditionalCardPersonAddressType”、“AutomaticRaiseCreditLimit”、“CardDeliveryTimeWeekDay” };

希望这能有所帮助。

当你正确实现List,但不包括System.Collections.Generic命名空间时,你收到的错误消息是误导性的,没有帮助:

编译器错误CS0308:非泛型类型List不能与类型参数一起使用。

PS -它会给出这个无用的错误,因为如果你没有指定你打算使用System.Collections.Generic.List,编译器会假设你正在尝试使用System.Windows.Documents.List。