假设我有一个高级别界面IRobot
public interface IRobot
{
Boolean DoAction(object action);
}
实现此接口的两个类
public class WalkingRobot : IRobot
{
public enum WalkAction { SLOW, FAST };
public new Boolean DoAction(object inAction)
{
WalkAction action = (WalkAction)inAction;
// Does the action based on argument
return true;
}
}
public class TalkingRobot : IRobot
{
public enum TalkAction { ENGLISH, GERMAN };
public new Boolean DoAction(object inAction)
{
TalkAction action = (TalkAction)inAction;
// Does the action based on argument
return true;
}
}
如果我的List<IRobot>
包含这两个类的实例
WalkingRobot walker = new WalkingRobot();
TalkingRobot talker = new TalkingRobot();
List<IRobot> robots = new List<>();
robots.Add(walker);
robots.Add(talker);
我是否能够遍历List<>
并将每个IRobot
与我创建的实例进行比较?
WalkAction wAction = WalkAction.FAST;
TalkAction tAction = TalkAction.ENGLISH;
foreach(IRobot robot in robots)
{
if(robot == walker)
robot.DoAction((object)wAction);
if(robot == talker)
robot.DoAction((object)tAction);
}
答案 0 :(得分:2)
除非您没有显示==
超载,否则您只是在比较两个引用是否相等 - 这很好。您甚至不需要将wAction
和tAction
投射到object
,因为您可以使用隐式转换:
foreach(IRobot robot in robots)
{
if (robot == walker)
{
robot.DoAction(wAction);
}
else if (robot == talker)
{
robot.DoAction(tAction);
}
}
这样可行,但总体而言,这不是一个很好的面向对象设计。你不是以同样的方式机器人,每个机器人都必须将他们的行动投射到正确的类型。
如果这是只是意味着将对象与==
进行比较的问题,那很好 - 但我会避开其余的代码设计。