我正在尝试迭代项目列表。这些项目都是公共(public)界面的一部分。它们如 this question 中所述.我想使用 foreach
循环来遍历它们,但根据它的类型执行不同的操作。
为了简单起见,假设我要执行的操作如下:
ProcessLine(MachineLine ML); //For MachineLines
ProcessLine(MachineCircle MC); //For MachineCircles
如何完成此迭代以考虑多种数据类型?
最佳答案
我会认真考虑在这种情况下这是否是最合适的设计。您确定 IMachine
接口(interface)不应该有 Process
方法吗?每台机器都可以适本地实现它,然后循环就变成了:
foreach (IMachine machine in machines)
{
machine.Process();
}
无论如何,要按要求回答问题,这是一种方法。这个想法是继续尝试对目标类型进行“推测性转换”,直到它成功或我们没有选择。这通常使用 as
运算符完成,后跟 null
-test。
IList<IMachine> machines = ...
foreach (IMachine machine in machines)
{
MachineLine machineLine = machine as MachineLine;
if (machineLine != null)
ProcessLine(machineLine);
else
{
MachineCircle machineCircle = machine as MachineCircle;
if (machineCircle != null)
ProcessCircle(machineCircle);
else throw new UnknownMachineException(...);
}
}
如您所见,这种模式很丑陋。对于更清洁的解决方案,您可能还想看看 C# - Is there a better alternative than this to 'switch on type'如果有大量的实现者。
关于c# - 迭代不同数据类型的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4361812/