Tim*_*mwi 32 c# syntax language-design
为什么会产生编译器错误:
class X { public void Add(string str) { Console.WriteLine(str); } }
static class Program
{
static void Main()
{
// error CS1922: Cannot initialize type 'X' with a collection initializer
// because it does not implement 'System.Collections.IEnumerable'
var x = new X { "string" };
}
}
Run Code Online (Sandbox Code Playgroud)
但这不是:
class X : IEnumerable
{
public void Add(string str) { Console.WriteLine(str); }
IEnumerator IEnumerable.GetEnumerator()
{
// Try to blow up horribly!
throw new NotImplementedException();
}
}
static class Program
{
static void Main()
{
// prints “string” and doesn’t throw
var x = new X { "string" };
}
}
Run Code Online (Sandbox Code Playgroud)
什么是限制的集合初始化的原因-这是一个调用语法糖Add
的方法-以实现不接口的类有一个Add
方法和不使用?
Jon*_*eet 26
一个对象初始化没有; 一个集合初始化呢.这样它就可以应用于真正代表集合的类,而不仅仅是具有Add
方法的任意类.我不得不承认,我经常" IEnumerable
明确地"实现" 只是为了允许集合初始化器 - 但是NotImplementedException
从中抛出了一个GetEnumerator()
.
请注意,在C#3的开发早期,集合初始化程序必须实现ICollection<T>
,但发现它过于严格.Mads Torgersen 在2006年发表了关于这一变化以及背后需要的原因的博客IEnumerable
.