我正在查看this blog ,其中解释了foreach
可以在不实施IEnumerable
的情况下得到支持。但是没有详细介绍实施。
我正在寻找一个如何在不实施foreach
的情况下支持IEnumerable
的示例。
编辑:感谢@Sam我的评论,我得到了我想要的东西。 (见下面的答案)
答案 0 :(得分:4)
这是一个不实现IEnumerable
或任何接口的类:
public class Foo
{
public IEnumerator<int> GetEnumerator()
{
yield return 1;
yield return 2;
}
}
你可以foreach
这样:
foreach (int n in new Foo())
Console.WriteLine(n);
这将打印出来:
1
2
答案 1 :(得分:1)
感谢@Sam我的评论,我能够在this page上调整代码并将以下内容放在一起,而不使用IEnumerable或IEnumerator:
//Person Object
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
string firstName;
public string lastName;
}
//****Object Collection.
//****This class usually needs to implement IEnumerable
//****But we are avoiding that here.
public class People
{
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 PeopleEnumSimulator GetEnumerator()
{
return new PeopleEnumSimulator(_people);
}
public class PeopleEnumSimulator
{
public Person[] _people;
int position = -1;
public PeopleEnumSimulator(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
}
//****Now, Use the Foreach
Person[] myPeople = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(myPeople);
foreach (Person p in peopleList)
Response.Write(p.firstName + " " + p.lastName);
//****************************************
//******** A Generic Implementation********
public class People<T>
{
private T[] _people;
public People(T[] pArray)
{
_people = new T[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
public PeopleEnumSimulator GetEnumerator()
{
return new PeopleEnumSimulator(_people);
}
public class PeopleEnumSimulator
{
public T[] _people;
int position = -1;
public PeopleEnumSimulator(T[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
public T Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
}
// use the foreach
//For Type Person
People<Person> peopleList = new People<Person>(myPeople);
foreach (Person p in peopleList)
Response.Write(p.firstName + " " + p.lastName);
//break
Response.Write(" </br></br></br> ");
//For Type Int
int[] n3 = { 2, 4, 6, 8 };
People<int> intList = new People<int>(n3);
foreach (int p in intList)
Response.Write(p);