需求:先需编写一个程序,用栈(Stack)进行进栈和出栈操作,并对栈中的元素进行运算。
方案一:假设元素为int类型,则可使用代码:
方案一:假设元素为int类型,则可使用代码:
- class Stack
- {
- private int[] items;
- private int count;
- public Stack(int size)
- {
- items=new int [size];
- count=0;
- }
- public void Push(int x)
- {
- items[count++]=x;
- }
- public int Pop()
- {
- return items[--count];
- }
- }
客户代码:
- class Test
- {
- static void Main()
- {
- Stack s=new Stack (10);
- s.Push(111);
- s.Push(222);
- Console.WriteLine (s.Pop ()+s.Pop ());
- }
- }
然而,现在需求发生变化。客户要求使用double类型,甚至还要支持string!这样考虑用到弱类型object。
修改代码如下:
- class Stack
- {
- private object[] items;
- private int count;
- public Stack(int size)
- {
- items=new object [size];
- count=0;
- }
- public void Push(object x)
- {
- items[count++]=x;
- }
- public object Pop()
- {
- return items[--count];
- }
- }
// 客户代码
- class Test
- {
- static void Main()
- {
- Stack s=new Stack (10);
- s.Push("111");
- s.Push("222");
- Console.WriteLine ((string)s.Pop ()+(string)s.Pop ());
- }
- class Stack<T>
- {
- private T [] items;
- private int count;
- public Stack(int size)
- {
- items=new T[size];
- }
- public void Push(T x)
- {
- items[count++]=x;
- }
- public T Pop()
- {
- return items[--count];
- }
- }
- class Test
- {
- static void Main()
- {
- // int
- Stack<int> s1=new Stack<int> (10);
- s1.Push (111);
- s1.Push (222);
- Console.WriteLine (s1.Pop ()+s1.Pop ());
- // double
- Stack<double> s2=new Stack<double> (10);
- s2.Push (111.1);
- s2.Push (222.2);
- Console.WriteLine (s2.Pop ()+s2.Pop ());
- // string
- Stack<string > s3=new Stack<string > (10);
- s3.Push ("111");
- s3.Push ("222");
- Console.WriteLine (s3.Pop ()+s3.Pop ());
- }
- }