2012-02-23 139 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