【问题标题】:Using an implicitly-typed array in class initializer在类初始值设定项中使用隐式类型数组
【发布时间】:2016-05-17 07:22:53
【问题描述】:

考虑以下几点:

public class Foo
{
    public List<int> ListProp { get; set; } = new List<int>();
    public int[] ArrayProp { get; set; } = new int[3];
}

public static void Main()
{
    new Foo
    {
        // This works, but does not call the setter for ListProp.
        ListProp = { 1, 2, 3 },

        // This gives a compiler error: 'int[]' does not contain a
        // definition for 'Add' and no extension method 'Add' accepting
        // a first argument of type 'int[]' could be found (are you
        // missing a using directive or an assembly reference?)
        ArrayProp = { 4, 5, 6 }
    };
}

我很想知道发生了什么。 ListProp 设置器不会被调用。我们尝试分配 ArrayProp 的编译器错误表明,在内部,此分配将尝试调用“添加”方法。

PS:显然,代码可以这样工作:ArrayProp = new int[] { 4, 5, 6 } 但这并不能满足我的好奇心 :)

【问题讨论】:

    标签: c# arrays collections initializer implicit-typing


    【解决方案1】:

    ListProp 设置器没有被调用

    因为它实际上并没有被重新设置。在这种情况下,collection initializer 语法糖实际上会调用List&lt;T&gt;.Add。它基本上是在做:

    public static void Main()
    {
        Foo expr_05 = new Foo();
        expr_05.ListProp.Add(1);
        expr_05.ListProp.Add(2);
        expr_05.ListProp.Add(3);
    }
    

    我们尝试分配 ArrayProp 的编译器错误表明 在内部,此分配将尝试调用“添加”方法。

    没错,如上所述,集合初始化器只不过是在给定集合上调用Add 方法的语法糖。由于int[] 或任何与此相关的数组不具有Add 方法,您会收到编译时错误。

    【讨论】:

    • 感谢 Yuval,很有趣!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 2011-05-22
    • 2012-09-06
    • 2014-01-23
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多