例如,想设计一个堆栈,我们的目标时明确的:既是确定对哪种数据的操作
using System;
public class Starter{
public static void Main(){
StackInt stack=new StackInt(5);
stack.Push(10);
stack.Push(15);
Console.WriteLine("Pushed 3 values");
stack.ListItems();
stack.Pop();
Console.WriteLine("Popped 1 value");
stack.ListItems();
}
}
public class StackInt {
public StackInt(int firstItem) {
list=new int[1] {firstItem};
}
public int Pop() {
if(top!=0) {
return list[--top];
}
throw new Exception("Stack empty");
}
public void Push(int topitem) {
++top;
if(top==list.Length) {
int [] temp=new int[top+1];
Array.Copy(list, temp, top);
list=temp ;
}
list[top]=topitem;
}
public void ListItems () {
for(int item=0;item<=top;++item) {
Console.WriteLine(list[item]);
}
}
private int [] list;
private int top=0;
}