C#嵌套初始化陌生感
作者:互联网
在这些初始化语句编译的前提下
List<int> l = new List<int> { 1, 2, 3 };
Dictionary<int, int> d = new Dictionary<int, int> { [1] = 11, [2] = 22 };
Foo f = new Foo { Bar = new List<int>() };
这不会
List<int> l = { 1, 2, 3 };
Dictionary<int, int> d = { [1] = 11, [2] = 22 };
Foo f = { Bar = new List<int>() };
我有一个关于嵌套初始化的问题.鉴于以下课程
public class Foo {
public List<int> Bar { get; set; } = new List<int>();
public Dictionary<int, Foo> Baz { get; set; } = new Dictionary<int, Foo>();
}
我偶然发现你可以这样做:
Foo f = new Foo {
Bar = { 1, 2, 3 },
Baz = {
[1] = {
Bar = { 4, 5, 6 }
}
}
};
虽然它确实编译它会抛出一个KeyNotFoundException.所以我将属性更改为
public List<int> Bar { get; set; } = new List<int> { 4, 5, 6 };
public Dictionary<int, Foo> Baz { get; set; }
= new Dictionary<int, Foo> { [1] = new Foo { Bar = new List<int>() { 1, 2, 3 } } };
假设这是替换现有成员的一些不寻常的表示法.现在初始化抛出StackOverflowException.
所以我的问题是,为什么表达式甚至可以编译?该怎么办?我觉得我必须遗漏一些非常明显的东西.
解决方法:
So my question is, why does the expression even compile?
它是一个带有集合初始化值的对象初始值设定项.从C#规范部分7.6.10.2:
A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property, the elements given in the initializer are added to the collection referenced by the field or property.
所以你的代码大致相当于:
Foo tmp = new Foo();
tmp.Bar.Add(1);
tmp.Bar.Add(2);
tmp.Bar.Add(3);
tmp.Baz[1].Bar.Add(4); // This will throw KeyNotFoundException if Baz is empty
tmp.Baz[1].Bar.Add(5);
tmp.Baz[1].Bar.Add(6);
Foo f = tmp;
您的初始化版本将抛出StackOverflowException,因为Foo的初始化程序需要创建一个新的Foo实例,它需要创建一个新的Foo实例等.
标签:c,syntax,semantics,c-6-0 来源: https://codeday.me/bug/20190611/1218261.html