为什么不添加正确的项目?

时间:2012-03-07 12:47:38

标签: c# arrays

    static void Main(string[] args)
    {
        minlist<authorinfo> aif = new minlist<authorinfo>();
        aif.Add(new authorinfo("The Count of Monte Cristo","Alexandre", "Dumas", 1844));
        aif.Add(new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972));
        aif.Add(new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844));
        aif.Add(new authorinfo("2001: A Space Odyssey", "Arthur", "Clark", 1968));

4项,

class minlist<T>
{
    T[] storage = new T[3];
    T[] storagereplace = new T[5];
    T[] storagereplace2 = new T[10];
    int spot = 0;

    public void Add(T obj)
    {
        if (spot != 3)
        {
            storage[spot] = obj;
            spot++;
            if (spot == 3)
            {
                int spot2 = spot;

                storage.CopyTo(storagereplace, 0);
                storagereplace[spot2] = obj;
                spot2++;
                foreach (T k in storagereplace)
                {
                    Console.WriteLine(k);
                }
                Console.WriteLine(spot2);
            }
        }

结果:

Alexandre,Dumas,基督山伯爵,1844年

亚瑟,克拉克,1972年与拉玛约会,

Alexandre,Dumas,The Three Musketeers,1844

Alexandre,Dumas,The Three Musketeers,1844

为什么重复最后一次而不是添加2001?

1 个答案:

答案 0 :(得分:3)

因为这个:

   if (spot != 3)
   {
       storage[spot] = obj;
       spot++;
       if (spot == 3)  
       {
   // etc.

如果点是2,请考虑此代码的作用。它设置storage[2] = obj,然后将1添加到spot,找出spot == 3并设置storagereplace[3] = obj

出于好奇:为什么要以这种方式实现列表类而不是使用现有的List<T>类?

但是,你的班级还有很多问题。例如,如果spot大于3,storage[spot] = obj将导致异常。

除非你有充分的理由去实现自己的集合类,否则最好使用List<T>或类似的东西。

相关问题