我想为下一段代码使用集合初始值设定项:
public Dictionary<int, string> GetNames()
{
Dictionary<int, string> names = new Dictionary<int, string>();
names.Add(1, "Adam");
names.Add(2, "Bart");
names.Add(3, "Charlie");
return names;
}
Run Code Online (Sandbox Code Playgroud)
通常它应该是这样的:
return new Dictionary<int, string>
{
1, "Adam",
2, "Bart"
...
Run Code Online (Sandbox Code Playgroud)
但是这个的正确语法是什么?
我正在查看C#集合初始化程序,发现实现非常务实,但也与C#中的任何其他内容完全不同
我能够创建这样的代码:
using System;
using System.Collections;
class Program
{
static void Main()
{
Test test = new Test { 1, 2, 3 };
}
}
class Test : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void Add(int i) { }
}
Run Code Online (Sandbox Code Playgroud)
由于我满足了编译器(已实现IEnumerable和a public void Add)的最低要求,因此无效,但显然没有价值.
我想知道是什么阻止了C#团队创建更严格的要求?换句话说,为了编译这种语法,为什么编译器不要求类型实现ICollection?这似乎更符合其他C#功能的精神.