考虑以下几点:
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/