C# foreach in 循环的问题

来源:百度知道 编辑:UC知道 时间:2024/05/14 12:24:06
题:能用foreach遍历访问的对象需要实现 ______________接口或声明______________方法的类型。
答案:能用foreach遍历访问的对象必须是集合或数组对象,而这些都是靠实现超级接口IEnumerator或被声明 GetEnumerator 方法的类型

但是我在平常使用foreach in 的时候都是直接用的呀,也没出什么问题呀。请问,这是为什么呢。 如果按题目中问的那样去实现超级接口IEnumerator或被声明 GetEnumerator 方法的类型,应该怎样去做呢? 谢谢!
就是这样直接使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CAforeach_in
{
class Program
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}

}
}
}

是不是集合和泛型就要实现那些接口和方法,那请问是怎么实现的呢? 请举个例子, 谢谢!

平常使用foreach in 的时候都是用的系统定义好的集合类(实现ICollection接口)。比如 arrayList,stringDictionary ,数组等。这些是平台封装好的,已近实现了IEnumerator 接口了。
要让自己写的类也能时候foreach 就必须 在编写类的时候实现该接口。
这样就可以事后foreach遍历了。
比如 定义一个 people 的类,实现了IEnumerator接口。
有一个数组 People[] tempPeople ,
那么 就可以用:
foreach( p in tempPeople)
{
console.writeline(p.name);
}

这样就免去了用for 循环的麻烦。

至于怎么样去实现Iemumerator接口。查一下MSDN 就可以啦。找本厚点的书看看也行。

请说明你平常是怎么用的
foreach in 的时候都是直接用
foreach (int i in fibarray)
集合或数组对象i
数组fibarray
怎么实现的 这些都是靠实现超级接口IEnumerator或被声明 GetEnumerator 方法的类型
数组fibarray 现超级接口IEnumerator或被声明 GetEnumerator 方法的类型

foreach(类型 a in 类型aaa)

实现超级接口IEnumerator或被声明 GetEnumerator 方法的类型是上面的
类型aaa

foreach(type a in list)
{

}

题目的意思是指,list类必须是集合或数组对象,而这些都是靠实现超级接口IEnumerator或被声明 GetEnumerator 方法的类型

因为你用到的都已经实现了这两个接口中的一个了,所以不需要你再重写这个方法