繁体   English   中英

为什么集合初始化表达式需要实现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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM