Почему выражение инициализатора коллекции требует реализации IEnumerable?

Почему возникает ошибка компилятора:

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 и который не используется?

31
задан Dirk Vollmar 15 September 2010 в 10:21
поделиться