首页 新闻 会员 周边

怎样为IEnumerator类型添加类型参数?

0
[待解决问题]

我在自学C#,看到泛型,在博客园上看到一篇利用自定义类来实现foreach循环的文章,想加深自己对泛型的理解,我就把文章中的代码粘过去运行一下,报错

说“使用泛型 类型“System.Collections.Generic.IEnumerator<T>”需要 1 个类型参数”。我就不知道怎么加类型参数了,博客中的作者还运行出了结果,为什么我运行就出错呢?先在这里谢谢大神的讲解。

代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication5
{
public class Person
{
string Name;
int Age;

public Person(string name, int age)
{
Name = name;
Age = age;
}

public override string ToString()
{
return "Name: " + Name + "\tAge: " + Age;
}
}
public class PeopleEnum : IEnumerator
{
private Person[] _people;
int position = -1;

public PeopleEnum(Person[] list)
{
_people = list;
}

public bool MoveNext()
{
position++;
return (position < _people.Length);
}

public void Reset()
{
position = -1;
}

public object Current
{
get
{
return _people[position];
}
}

}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];

}
}

public IEnumerator GetEnumerator()
{
return new PeopleEnum(_people);
}
}
class Program
{
static void Main(string[] args)
{
Person[] persons = new Person[]
{
new Person("aaa", 20),
new Person("bbb", 21),
new Person("ccc", 22)
};

People peopleList = new People(persons);

foreach (var item in peopleList)
{
System.Console.WriteLine(item);
}

System.Console.ReadKey();
}
}
}

不断学习啊的主页 不断学习啊 | 菜鸟二级 | 园豆:202
提问于:2017-02-13 15:05
< >
分享
所有回答(1)
1

添加明明空间

using System.Collections;

plina | 园豆:211 (菜鸟二级) | 2017-02-13 15:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册