c# - 在类初始值设定项中使用隐式类型数组

标签 c# arrays collections initializer implicit-typing

考虑以下几点:

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 setter。我们尝试分配 ArrayProp 的编译器错误表明在内部,此分配将尝试调用“Add”方法。

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

最佳答案

The ListProp setter doesn't get called

因为它实际上并没有被重新设置。 collection initializer语法糖实际上会调用 List<T>.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);
}

And the compiler error where we try to assign ArrayProp suggests that internally, this assignment will try to call an "Add" method.

没错,如上所述,集合初始化器只不过是调用 Add 的语法糖。给定集合上的方法。自 int[] ,或者与此相关的任何数组都没有 Add方法,你会得到一个编译时错误。

关于c# - 在类初始值设定项中使用隐式类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35255954/

相关文章:

collections - 在调用方法之前,Doctrine2 不会加载 Collection

java - 设置迭代器的并发修改异常

java - 哪个java集合允许重复键

c# - 如何在 Linux 命令行上通过 Mono 构建 C# 文件?

c# - 为关闭计算机而创建的 Windows 服务在计算机锁定时无法运行

ruby - Array.min 的复杂性

PHP 按行获取 MySQL 数据库作为关联数组

php - 在PHP数组中对列进行排序

C# 闭包变量作用域

c# - Repository.Checkout() 不会取消子模块更改