我有两个列表。两个列表的类型都继承自相同的基类型。我想遍历它们并执行仅使用基类功能的操作,而无需一个接一个地使用两个基本相同的 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;
}
最佳答案
这应该可以解决问题...
foreach (var item in list1.Concat<Base>(list2))
{
// Do your thing
}
编辑:我将 Union
更改为 Concat
,因为我认为它可能更合适。
关于c# - 遍历两个继承类(相同基类)的两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428849/