考虑以下:
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 }
但这并不能满足我的好奇心:)