001.
using
System.Collections;
002.
using
System.Collections.Generic;
003.
004.
namespace
GenericIteratorExample
005.
{
006.
public
class
Stack<T> : IEnumerable<T>
007.
{
008.
private
T[] values =
new
T[100];
009.
private
int
top = 0;
010.
011.
public
void
Push(T t) { values[top++] = t; }
012.
public
T Pop() {
return
values[--top]; }
013.
014.
015.
016.
public
IEnumerator<T> GetEnumerator()
017.
{
018.
for
(
int
i = top; --i >= 0; )
019.
{
020.
yield
return
values[i];
021.
}
022.
}
023.
024.
IEnumerator IEnumerable.GetEnumerator()
025.
{
026.
return
GetEnumerator();
027.
}
028.
029.
030.
public
IEnumerable<T> TopToBottom
031.
{
032.
get
033.
{
034.
035.
036.
037.
return
this
;
038.
}
039.
}
040.
041.
042.
public
IEnumerable<T> BottomToTop
043.
{
044.
get
045.
{
046.
for
(
int
i = 0; i < top; i++)
047.
{
048.
yield
return
values[i];
049.
}
050.
}
051.
}
052.
053.
054.
public
IEnumerable<T> TopN(
int
n)
055.
{
056.
057.
int
j = n >= top ? 0 : top - n;
058.
059.
for
(
int
i = top; --i >= j; )
060.
{
061.
yield
return
values[i];
062.
}
063.
}
064.
}
065.
066.
067.
068.
class
Test
069.
{
070.
static
void
Main()
071.
{
072.
Stack<
int
> s =
new
Stack<
int
>();
073.
for
(
int
i = 0; i < 10; i++)
074.
{
075.
s.Push(i);
076.
}
077.
078.
079.
080.
foreach
(
int
n
in
s)
081.
{
082.
System.Console.Write(
"{0} "
, n);
083.
}
084.
System.Console.WriteLine();
085.
086.
087.
088.
foreach
(
int
n
in
s.TopToBottom)
089.
{
090.
System.Console.Write(
"{0} "
, n);
091.
}
092.
System.Console.WriteLine();
093.
094.
095.
096.
foreach
(
int
n
in
s.BottomToTop)
097.
{
098.
System.Console.Write(
"{0} "
, n);
099.
}
100.
System.Console.WriteLine();
101.
102.
103.
104.
foreach
(
int
n
in
s.TopN(7))
105.
{
106.
System.Console.Write(
"{0} "
, n);
107.
}
108.
System.Console.WriteLine();
109.
}
110.
}
111.
}