需要IEnumerable的使用foreach循环? [英] Is IEnumerable required to use a foreach loop?

查看:201
本文介绍了需要IEnumerable的使用foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,当我正好可以用foreach循环?我一定要实现IEnumerable?

I was wondering, when exactly can I use the foreach loop? Do I have to implement IEnumerable?

推荐答案

有没有必要实现IEnumerable接口使用foreach语句。下面是从MSDN( http://msdn.microsoft.com/en-us/library/报价9yb8xew9.aspx ):

There is no need to implement the IEnumerable interface to use the foreach statement. Here is a quote from the MSDN (http://msdn.microsoft.com/en-us/library/9yb8xew9.aspx):

在C#中,也并非绝对必要的
的集合类要继承
IEnumerable和IEnumerator的,以
是用foreach兼容。只要
作为类具有所需的
的GetEnumerator,调用MoveNext,复位和
目前的成员,它将与
的foreach工作。省略接口有
让您
定义当前至
返回类型大于对象,其中
提供了类型安全更具体的优势。

In C#, it is not absolutely necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach. As long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of enabling you to define the return type of Current to be more specific than Object, which provides type-safety.

这篇关于需要IEnumerable的使用foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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