[英]cannot initialize type with a collection initializer because it does not implement ienumerable
[英]Why does a collection initializer expression require IEnumerable to be implemented?
為什么會產生編譯器錯誤:
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" };
}
}
但這不是:
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" };
}
}
什么是限制的集合初始化的原因-這是一個調用語法糖Add
方法-以實現其不具有的接口類Add
方法和不使用?
對象初始化器不會; 集合初始化程序。 這樣它就可以應用於真正代表集合的類,而不僅僅是具有Add
方法的任意類。 我必須承認,我經常明確地“實現” IEnumerable
,只是為了允許集合初始化器 - 但是從GetEnumerator()
拋出了一個NotImplementedException
。
請注意,在C#3開發的早期,集合初始化程序必須實現ICollection<T>
,但發現它過於嚴格。 Mads Torgersen在2006年發表了關於這一變化的博客 ,以及要求IEnumerable
背后的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.