【发布时间】:2017-05-18 20:35:07
【问题描述】:
在这些初始化语句可以编译的前提下
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。
所以我的问题是,为什么表达式甚至可以编译?它应该做什么?我觉得我一定错过了一些非常明显的东西。
【问题讨论】:
-
堆栈溢出仅仅是因为创建
Foo将创建一个Dictionary并创建一个Foo以添加到它,这反过来又创建一个Dictionary与Foo等等。 -
请注意,您可以将其更改为
Baz = { {1, new Foo { Bar = {4,5,6}}}};以使其工作,因为该符号使用Dictionary的Add(Tkey, TValue),在这种情况下,如果没有new Foo,它将无法编译。跨度>
标签: c# syntax semantics c#-6.0