代码之家  ›  专栏  ›  技术社区  ›  Timwi

为什么集合初始值设定项表达式需要实现IEnumerable?

  •  30
  • Timwi  · 技术社区  · 14 年前

    为什么会产生编译器错误:

    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 添加 方法和哪些没有使用?

    1 回复  |  直到 14 年前
        1
  •  28
  •   Jon Skeet    14 年前

    对象 初始值设定项没有;a 收集 初始值设定项没有。所以它被应用于真正代表集合的类,而不仅仅是具有 Add 方法。我不得不承认我经常“实施” IEnumerable 显式地,只允许集合初始值设定项-但抛出 NotImplementedException GetEnumerator() .

    ICollection<T> ,但这被认为限制太多。马德斯托格森 blogged about this change I可数 ,早在2006年。

    推荐文章