3 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以為此使用泛型。下面的addToList方法是一個(gè)通用方法,它接受任何類型的列表和對(duì)象來添加它。
public static <T> void addToList(final List<T> list, final T toAdd) {
list.add(toAdd);
}
public static void main(final String[] args) {
final List<Book> listBook = new ArrayList<Book>();
final List<Pen> listPen = new ArrayList<Pen>();
addToList(listPen, new Pen());
addToList(listBook, new Book());
}
注意(不可能):在您的代碼中,您創(chuàng)建了 的對(duì)象List,而 List 是一個(gè)接口,因此您無法創(chuàng)建 List 的對(duì)象。相反,它應(yīng)該是ArrayList().

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果您只尋找一種方法(即 Add()),這里是完整的代碼。
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Book
{
public string name;
public int id;
public Book(string name, int id)
{
this.name = name;
this.id = id;
}
}
public class Pen
{
public string name;
public int id;
public Pen(string name, int id)
{
this.name = name;
this.id = id;
}
}
public class Program
{
static List<Book> listBook = new List<Book>();
static List<Pen> listPen = new List<Pen>();
public static void Main(string[] args)
{
listBook.Add(new Book
(
"Book1",
1
));
listBook.Add(new Book
("Book2",
2
));
listPen.Add(new Pen
("Pen1",
1
));
listPen.Add(new Pen("Pen2", 2));
//Testing with new book list
List<Book> newListBook = new List<Book>();
newListBook.Add(new Book
("Book3",
3
));
newListBook.Add(new Book
("Book4",
4
));
Add(newListBook);
foreach (var item in listBook)
{
Console.WriteLine(item.name);
}
List<Pen> newListPen = new List<Pen>();
newListPen.Add(new Pen
("Pen3",
3
));
newListPen.Add(new Pen
("Pen4",
4
));
Add(newListPen);
foreach (var item in listPen)
{
Console.WriteLine(item.name);
}
Console.ReadLine();
}
public static void Add<T>(IEnumerable<T> obj)
{
foreach (var item in obj)
{
if (item is Book)
{
listBook.Add(item as Book);
}
if (item is Pen)
{
listPen.Add(item as Pen);
}
}
}
}
}

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
不確定我是否正確理解你的問題,所以我會(huì)根據(jù)你使用 C# 的假設(shè)提出一些解決方案:
情況1:如果你只是想向列表中添加一個(gè)項(xiàng)目,那么就使用Ling。
using System.Linq;
List<Book> books = new List<Book>();
Book myBook = new Book();
books.Add(myBook);
情況2:如果你想創(chuàng)建一個(gè)適用于任何數(shù)據(jù)類型的方法,那么編寫一個(gè)模板
public void MyAddMethod<T>(ref List<T> list, T item)
{
list.Add(item);
}
List<Book> book = new List<Book>();
Book myBook = new Book();
MyAddMethod(ref books, myBook);
這是我最好的選擇。希望這可以幫助。
添加回答
舉報(bào)