【问题标题】:Creating List from initializer从初始化程序创建列表
【发布时间】:2014-02-18 10:44:13
【问题描述】:

有什么区别

var list = new List<UserType>
{
    new UserType(...),
    new UserType(...),
};

var list = new List<UserType>()
{
    new UserType(...),
    new UserType(...),
};

?

我以前总是使用第二个,认为我只需要调用列表的无参数(或任何其他)构造函数...

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • ReSharper 之类的工具会通知您在使用初始化程序时可以删除 ()。假设你没有参数。

标签: c# list initializer


【解决方案1】:

都是一样的。来自MSDN

对象初始值设定项语法使您能够为 构造函数或省略参数(和括号语法)

同样的规则适用于列表和普通对象初始化器:

var foo = new Bar {
    Prop = "value"
};

【讨论】:

  • 您应该注意,这只是语法糖,因为编译器只是将其转换为 .Add() 调用:“通过使用集合初始化程序,您不必指定对 Add 方法的多次调用源代码中的类;编译器添加调用。"
  • 感谢来源。
【解决方案2】:

不,没有区别。生成的 IL一模一样

IL_0001:  newobj      System.Collections.Generic.List<UserQuery+UserType>..ctor
IL_0006:  stloc.1     // <>g__initLocal0
IL_0007:  ldloc.1     // <>g__initLocal0
IL_0008:  newobj      UserQuery+UserType..ctor
IL_000D:  callvirt    System.Collections.Generic.List<UserQuery+UserType>.Add
IL_0012:  nop         
IL_0013:  ldloc.1     // <>g__initLocal0
IL_0014:  newobj      UserQuery+UserType..ctor
IL_0019:  callvirt    System.Collections.Generic.List<UserQuery+UserType>.Add
IL_001E:  nop         
IL_001F:  ldloc.1     // <>g__initLocal0
IL_0020:  stloc.0     // list

即使实例化一个新的List 并自己调用.Add 也非常相似,即:

var list = new List<UserType>();

list.Add(new UserType());
list.Add(new UserType());

...生成:

IL_0001:  newobj      System.Collections.Generic.List<UserQuery+UserType>..ctor
IL_0006:  stloc.0     // list
IL_0007:  ldloc.0     // list
IL_0008:  newobj      UserQuery+UserType..ctor
IL_000D:  callvirt    System.Collections.Generic.List<UserQuery+UserType>.Add
IL_0012:  nop         
IL_0013:  ldloc.0     // list
IL_0014:  newobj      UserQuery+UserType..ctor
IL_0019:  callvirt    System.Collections.Generic.List<UserQuery+UserType>.Add

这略有不同——看起来不同之处在于生成一个临时变量并将其分配给list,而不是直接创建和操作list

【讨论】:

  • 感谢您提供详细信息。
猜你喜欢
  • 2012-02-16
  • 1970-01-01
  • 2014-02-23
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多