3 回答

TA貢獻1859條經驗 獲得超6個贊
您可以為此使用泛型。下面的addToList方法是一個通用方法,它接受任何類型的列表和對象來添加它。
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());
}
注意(不可能):在您的代碼中,您創建了 的對象List,而 List 是一個接口,因此您無法創建 List 的對象。相反,它應該是ArrayList().

TA貢獻1830條經驗 獲得超9個贊
如果您只尋找一種方法(即 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貢獻1826條經驗 獲得超6個贊
不確定我是否正確理解你的問題,所以我會根據你使用 C# 的假設提出一些解決方案:
情況1:如果你只是想向列表中添加一個項目,那么就使用Ling。
using System.Linq;
List<Book> books = new List<Book>();
Book myBook = new Book();
books.Add(myBook);
情況2:如果你想創建一個適用于任何數據類型的方法,那么編寫一個模板
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);
這是我最好的選擇。希望這可以幫助。
添加回答
舉報