我在自学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();
}
}
}
添加明明空间
using System.Collections;