日期:2014-05-17  浏览次数:20702 次

泛型,模仿堆栈的类,报错。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class MyStack<T>
    {
        public T[] Myarray;
        public int count;
        public MyStack(int m)
        {
            Myarray = new T[m];
            count = 0;
        }

        public void push(T a)
        {
            Myarray[count++] = a;

        }
        public T pull()
        {
            return Myarray[--count];
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            MyStack<int> myStack = new MyStack<int>(10);
            myStack.push(1);
            myStack.push(2);
            myStack.push(3);
            for (int i = 0; 1 < 3; i++)
            {
                Console.WriteLine(myStack.pull());
            }

          
        }
    }
}
------解决方案--------------------
            for (int i = 0; 1 < 3; i++)
             {
                 Console.WriteLine(myStack.pull());
             }

1<3
死循环呢,下标早就越界了。再一个,你写的类型不应该有这种缺陷,需要解决。
------解决方案--------------------
引用:
C# code?1234            for (int i = 0; 1 < 3; i++)             {