[英]Using an implicitly-typed array in class initializer
考虑以下:
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 }
但是这不满足我的好奇心:)
ListProp setter不会被调用
因为它实际上并没有被重新设定。 在这种情况下, 集合初始化程序语法糖实际上会调用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);
}
我们尝试分配ArrayProp的编译器错误表明,在内部,此赋值将尝试调用“Add”方法。
这是正确的,如上所述,集合初始值设定项只不过是用于在给定集合上调用Add
方法的语法糖。 由于int[]
或任何数组都没有Add
方法,因此会出现编译时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.