Why does a collection initializer expression require IEnumerable to be implemented?

后端 未结 1 1612
广开言路
广开言路 2020-12-15 03:10

Why does this generate a compiler error:

class X { public void Add(string str) { Console.WriteLine(str); } }

static class Program
{
    static void Main()
          


        
相关标签:
1条回答
  • 2020-12-15 03:51

    An object initializer doesn't; a collection initializer does. It's so that it's applied to classes which really represent collections, rather than just arbitrary ones which have an Add method. I have to admit that every so often I've "implemented" IEnumerable explicitly, just to allow collection initializers - but thrown a NotImplementedException from GetEnumerator().

    Note that early in C# 3's development, collection initializers had to implement ICollection<T>, but that was found to be too restrictive. Mads Torgersen blogged about this change, and the reason behind requiring IEnumerable, back in 2006.

    0 讨论(0)
提交回复
热议问题