当 class 的两个实例被输入为基础 class 和 subclass 时测试它们的相等性?
Testing equality of two instances of a class when they are typed as their base class and subclass?
假设我有一个高级接口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);
}
除非有一个您没有显示的 ==
重载,否则您只是比较两个引用是否相等 - 没关系。您甚至不需要将 wAction
和 tAction
转换为 object
,因为您可以使用隐式转换:
foreach(IRobot robot in robots)
{
if (robot == walker)
{
robot.DoAction(wAction);
}
else if (robot == talker)
{
robot.DoAction(tAction);
}
}
这会起作用,但总的来说,这在很长一段时间内都不是很好的面向对象设计。你和机器人不一样,每个机器人都必须将他们的动作转换为正确的类型。
如果这 只是 是关于将对象与 ==
进行比较的问题,那很好 - 但我会避开其余代码一个设计。
假设我有一个高级接口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);
}
除非有一个您没有显示的 ==
重载,否则您只是比较两个引用是否相等 - 没关系。您甚至不需要将 wAction
和 tAction
转换为 object
,因为您可以使用隐式转换:
foreach(IRobot robot in robots)
{
if (robot == walker)
{
robot.DoAction(wAction);
}
else if (robot == talker)
{
robot.DoAction(tAction);
}
}
这会起作用,但总的来说,这在很长一段时间内都不是很好的面向对象设计。你和机器人不一样,每个机器人都必须将他们的动作转换为正确的类型。
如果这 只是 是关于将对象与 ==
进行比较的问题,那很好 - 但我会避开其余代码一个设计。