1

我想在类中使用集合初始化器值初始化列表,以使其可用于单独的函数:

public Form1()
{
    InitializeComponent();
}

List<string> list = new List<string>() {"one", "two", "three"}; 

带括号和不带括号的列表有什么区别,哪个适合这种情况:

List<string> list = new List<string> {"one", "two", "three"}; 
4

2 回答 2

1

打电话

List<string> list = new List<string> {"one", "two", "three"}; 

只是一个简写并隐式调用默认构造函数:

List<string> list = new List<string>() {"one", "two", "three"}; 

也看生成的IL代码,是一样的:

List<string> list = new List<string>() {"one"}; 
List<string> list2 = new List<string> {"one"}; 

变成:

IL_0001:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
IL_0006:  stloc.2
IL_0007:  ldloc.2
IL_0008:  ldstr      "one"
IL_000d:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
IL_0012:  nop
IL_0013:  ldloc.2
IL_0014:  stloc.0

IL_0015:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
IL_001a:  stloc.3
IL_001b:  ldloc.3
IL_001c:  ldstr      "one"
IL_0021:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
IL_0026:  nop
IL_0027:  ldloc.3
IL_0028:  stloc.1

您会看到{}符号只是语法糖,它首先调用默认构造函数,然后在{}usingList<T>.Add()方法中添加每个元素。所以你的代码相当于:

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
于 2017-06-02T06:13:38.103 回答
0

在括号()(构造函数)中,您可以传递一些特定参数,例如列表的初始大小等。使用{ }括号时,您只需使用一些起始值初始化列表。

在您的情况下,您将使用哪个没有区别,两者都将具有与您使用默认构造函数调用类似的效果。

于 2017-06-02T06:11:10.087 回答