一个数组,索引,泛型,迭代的例子
迭代就是指循环,迭代器是指实现该循环的一种方式 ,也是一种设计模式。
using System;
using System.Collections.Generic;
using System.Text;
namespace diedai2
{
public class Stack<T> : IEnumerable<T>
{
//数组,索引,泛型,迭代
T[] items;
int idx;
public Stack(int size)
{
items = new T[size];
}
public void Push(T t)
{
items[idx] = t; idx++;
}
public T Pop()
{
return items[--idx];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
for (int i = items.Length - 1; i >= 0; --i)
{
yield return items[i];
}
}
public IEnumerator<T> GetEnumerator()
{
for (int i = items.Length - 1; i >= 0; --i)
{
yield return items[i];
}
}
}
class Program
{
static void Main(string[] args)
{
Stack<int> stack = new Stack<int>(13);
stack.Push(100);
stack.Push(101);
stack.Push(103);
stack.Push(104);
stack.Push(105);
stack.Push(106);
stack.Push(107);
stack.Push(108);
stack.Push(109);
stack.Push(110);
stack.Push(111);
stack.Push(112);
foreach (int i in stack)
{
Console.WriteLine(i.ToString());
}
Console.Read();
}
}
}