【问题标题】:About collection initializers in c#关于 C# 中的集合初始化器
【发布时间】:2013-03-04 10:20:24
【问题描述】:

我承认我对 c# 的经验还很远,所以这可能很明显,但我不得不问——这两个代码示例之间有什么区别吗?如果不明显,第一条语句在 new 运算符的末尾省略 ()。在这种情况下有什么区别还是 () 只是多余的?

private static Dictionary<string, string> dict1 = new Dictionary<string, string>
{
    { "a", "A" },
    { "b", "B" }
};

private static Dictionary<string, string> dict2 = new Dictionary<string, string>()
{
    { "a", "A" },
    { "b", "B" }
};

【问题讨论】:

  • 除了让其他人阅读和/或支持您的代码的可读性之外,没有什么区别,我认为大多数 C# 编码人员都熟悉使用第二个示例声明 Dictionary 新的。还要记住,如果你创建一个 Dictionary&lt;string,string&gt; dict1 = new Dictionary&lt;string,string&gt;; 而没有 () 作为非方法,那么你会得到编译器错误
  • @DJ KRAZE,我知道Dictionary&lt;string,string&gt; dict1 = new Dictionary&lt;string,string&gt;; 不会编译,这就是为什么我的两个示例都能编译让我感到惊讶。
  • 声明方法和实例不同

标签: c# collections initializer


【解决方案1】:

在这种情况下有什么区别还是 () 只是多余的?

没有区别。使用集合初始化器时添加() 是可选的,但生成的编译IL 是相同的。

【讨论】:

    【解决方案2】:

    不,没有。如果你检查 IL 代码,你会发现两个构造函数调用之间没有区别:

    IL_0028:  newobj      System.Collections.Generic.Dictionary<System.String,System.String>..ctor
    IL_002D:  stloc.1     // <>g__initLocal1
    IL_002E:  ldloc.1     // <>g__initLocal1
    IL_002F:  ldstr       "a"
    IL_0034:  ldstr       "A"
    IL_0039:  callvirt    System.Collections.Generic.Dictionary<System.String,System.String>.Add
    IL_003E:  ldloc.1     // <>g__initLocal1
    IL_003F:  ldstr       "b"
    IL_0044:  ldstr       "B"
    IL_0049:  callvirt    System.Collections.Generic.Dictionary<System.String,System.String>.Add
    IL_004E:  ldloc.1     // <>g__initLocal1
    

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 2012-10-14
      • 2018-10-05
      • 1970-01-01
      • 2011-03-04
      • 2016-10-10
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      相关资源
      最近更新 更多