2012-02-23 55 views
0

我想弄清楚如何將對象添加到數組列表中,然後返回它。 我的代碼如下:在ArrayList中添加返回對象

 mediaTitleCollection = new ArrayList(); 

     public BookMedia CreateBookTitle(string title, string subtitle, string edition, string author, string genre, int weight, int units, string isbn, int pages, int chapters) 
     { 
      mediaTitleCollection.Add(new BookMedia(title, subtitle, edition, author, genre, weight, units, isbn, pages, chapters)); 
      // Return the object i have just added in mediaTitleCollection 
     } 

我已經嘗試了一些方法,並搜查了半個多小時,不能似乎找到我的問題得到妥善解決。在提前

感謝。

+0

下面的答案是正確的,如果你沒有檢查的項目是否添加成功與否 – Xitrum 2012-02-23 10:01:15

回答

3
mediaTitleCollection = new ArrayList(); 

    public BookMedia CreateBookTitle(string title, string subtitle, string edition, string author, string genre, int weight, int units, string isbn, int pages, int chapters) 
    { 
     BookMedia result=new BookMedia(title, subtitle, edition, author, genre, weight, units, isbn, pages, chapters); 
     mediaTitleCollection.Add(result); 
     // Return the object i have just added in mediaTitleCollection 
     return result; 
    } 
+0

非常感謝!正是我需要的。 – JavaCake 2012-02-23 10:06:42

0
mediaTitleCollection = new ArrayList(); 

public BookMedia CreateBookTitle(string title, string subtitle, string edition, string author, string genre, int weight, int units, string isbn, int pages, int chapters) 
{ 
    BookMedia book = new BookMedia(title, subtitle, edition, author, genre, weight, units, isbn, pages, chapters); 
    mediaTitleCollection.Add(book); 

    return book; 
      // Return the object i have just added in mediaTitleCollection 
} 
0
mediaTitleCollection = new ArrayList(); 

    public BookMedia CreateBookTitle(string title, string subtitle, string edition, string author, string genre, int weight, int units, string isbn, int pages, int chapters) 
    { 
     BookMedia bm = new BookMedia(title, subtitle, edition, author, genre, weight, units, isbn, pages, chapters); 
     mediaTitleCollection.Add(bm); 
     // Return the object i have just added in mediaTitleCollection 
     return bm; 
    } 
2
return mediaTitleCollection[mediaTitleCollection.Count-1];//After adding, it returns the last object(don't need to initialize a local scope variable) 
+0

這個是高效的。 – maxpayne 2012-05-22 09:22:18