如何初始化(使用c#初始化器)字符串列表?我已经尝试了下面的例子,但它不工作。
List<string> optionList = new List<string>
{
"AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
如何初始化(使用c#初始化器)字符串列表?我已经尝试了下面的例子,但它不工作。
List<string> optionList = new List<string>
{
"AdditionalCardPersonAddressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
}();
当前回答
一个非常酷的特性是列表初始化器也可以很好地用于自定义类:您只需实现IEnumerable接口并有一个名为Add的方法。
例如,如果你有一个这样的自定义类:
class MyCustomCollection : System.Collections.IEnumerable
{
List<string> _items = new List<string>();
public void Add(string item)
{
_items.Add(item);
}
public IEnumerator GetEnumerator()
{
return _items.GetEnumerator();
}
}
这是可行的:
var myTestCollection = new MyCustomCollection()
{
"item1",
"item2"
}
其他回答
如果您使用的是c# 9.0及更高版本,则可以使用新特性目标类型的new表达式Link
例子:
List<string> stringList = new(){"item1","item2", "item3"} ;
您还没有真正提出问题,但代码应该提出问题
List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"};
例如,在列表后面没有尾随()。
你的函数很好,但不能工作,因为你把()放在了最后一个}之后。如果将()移到顶部new List<string>()旁边,错误就会停止。
示例如下:
List<string> optionList = new List<string>()
{
"AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};
你可能忽略了一些没有被提及的事情。我认为这可能是你遇到的问题,因为我怀疑你已经尝试删除尾随(),仍然得到一个错误。
首先,就像其他人在这里提到的,在你的例子中,你确实需要删除尾随();
但是,还要注意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。
只需在最后删除()即可。
List<string> optionList = new List<string>
{ "AdditionalCardPersonAdressType", /* rest of elements */ };