我有兩個列表。兩個列表的類型都從相同的基本類型繼承。我想遍歷它們,並執行只使用基類的功能而沒有兩個基本相同的foreach循環的操作。迭代兩個繼承類(相同基類)的兩個列表
我不能將列表複製到另一個列表或類似的東西,因爲我需要在操作完成後單獨使用列表的原始形式。
有沒有辦法做到這一點,而不寫一個函數?
class Program
{
static void Main(string[] args)
{
// I have two lists of inherited classes
List<Babby1> list1 = returnBabby1();
List<Babby2> list2 = returnBabby2();
// I want to iterate through both, and do the same thing, which is a part
// of the base class functionality.
// Basically I want this to be a single foreach loop.
foreach (Babby1 item in list1)
item.var = 50;
foreach (Babby2 item in list2)
item.var = 50;
// I have to send them as separate lists, the type being the original (inherited) class
sendBabby1(list1);
sendBabby2(list2);
}
static void sendBabby1(List<Babby1> list)
{
}
static void sendBabby2(List<Babby2> list)
{
}
static List<Babby1> returnBabby1()
{
return new List<Babby1>();
}
static List<Babby2> returnBabby2()
{
return new List<Babby2>();
}
}
class Base
{
public int var;
}
class Babby1 : Base
{
public int var1;
}
class Babby2 : Base
{
public int var2;
}
你有兩個單獨的列表,所以你不能沒有建立新的名單一一列舉爲一體。 – slugster