2012-03-07 58 views
-1
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); 
      } 
     } 

结果:

亚历山大,大仲马,基督山的伯爵,1844年

阿瑟·克拉克,与拉玛相会,1972年

亚历山大,杜马斯,三剑客,1844

亚历山大,杜马斯,三剑客,1844

为什么它重复了最后一个而不是2001年?

回答

3

因为这样:

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

想想这个代码做什么,如果斑点2.设置storage[2] = obj,然后加1被发现,发现该spot == 3并设置storagereplace[3] = obj了。

只是出于好奇:你为什么要实现你的列表类,而不是使用现有的List<T>类?

尽管如此,你的班级还存在不少问题。就像,如果现货大于3,storage[spot] = obj将导致异常。

更好的使用List<T>或类似的东西,除非你有一个很好的理由来实现你自己的集合类。

+0

你确定要放置点++和方法的结束吗?当我这样做时什么都没有显示出来。 – saturn 2012-03-07 13:07:49

+0

不,我修改了我的答案。如果不需要创建自己的List类,请更好地使用列表。 – Botz3000 2012-03-07 13:37:19

相关问题