c#中迭代器的问题

来源:百度知道 编辑:UC知道 时间:2024/08/22 08:55:27
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{Students student=new Students();
foreach(object mystudents in student)
{ Console.WriteLine(mystudents); }
Console.ReadLine();
}
}
class Students
{
string student1 = "甲";
string student2 = "乙";
public string Student1
{ get { return student1; } set { student1 = value; } }
public string Student2
{ get { return student2; } set { student2 = value; } }

}

}

错误:consoleapplication9.Students不包含getenumerator的公共定义,因此foreach语句不能作用于consoleapplication9.Students类型的变量

教材上最后还要加上一部分才对
public System.Collections.IEnumerator GetEnumerator()
{
for

用到了 你自己调试一下就知道
这个接口就是专门给foreach用的
没有它就不能foreach

用到了
他们都继承了这个接口 你看数组的类型是Array
而Array都继承了这个接口

必须实现 IEnumerable 接口以支持 foreach 语法。
-----------------------------------------------
数组类型是从抽象基类型 Array 派生的引用类型。由于此类型实现了 IEnumerable 和 IEnumerable<T>,因此可以对 C# 中的所有数组使用 foreach 迭代。