2012-03-07 57 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

相關問題