为什么一个集合初始化表达式需要的IEnumerable中实现? [英] Why does a collection initializer expression require IEnumerable to be implemented?

查看:583
本文介绍了为什么一个集合初始化表达式需要的IEnumerable中实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这生成编译器错误:

Why does this generate a compiler error:

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" };
    }
}



但这并不:

but this doesn’t:

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" };
    }
}



什么是限制集合初始化的原因 - 这是语法糖到添加方法的调用 - 来实现它没有一个接口的类的有无的一个添加方法和未使用的?

What is the reason for restricting collection initializers — which are syntactic sugar for a call to an Add method — to classes that implement an interface which doesn’t have an Add method and which isn’t used?

推荐答案

这是对象的初始化没有按'吨;一个的的初始化一样。它是如此,它的应用类这实际上代表的集合,而不仅仅是那些随意其中有一个添加方法。我不得不承认,每隔一段时间我实现的IEnumerable 明确,只允许集合初始化 - 但抛出 NotImplementedException 的GetEnumerator()

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().

请注意在C#3的发展早期,集合初始化不得不实施的ICollection< T> ,但被认为是过于严格。 MADS托格森博客上讲述这个变化和背后需要的IEnumerable ,早在2006年。

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.

这篇关于为什么一个集合初始化表达式需要的IEnumerable中实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆