【发布时间】:2010-10-02 08:37:13
【问题描述】:
我在查看 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) { }
}
因为我已经满足了编译器的最低要求(实现了IEnumerable 和public void Add),所以这可行,但显然没有任何价值。
我想知道是什么阻止了 C# 团队创建更严格的要求集?换句话说,为什么为了编译这个语法,编译器不要求类型实现ICollection?这似乎更符合其他 C# 功能的精神。
【问题讨论】:
-
请注意 Web 开发人员:如果您尝试将该类的实例序列化为 JSON,则会引发 NotImplementedException(实现 IEnumerable 会导致序列化程序遍历对象)
标签: c# collections