我有两个列表。两个列表的类型都从相同的基本类型继承。我想遍历它们,并执行只使用基类的功能而没有两个基本相同的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