多态如何替换循环内的if-else语句? [英] How can Polymorphism replace an if-else statement inside of a loop?
问题描述
多态如何在循环中替换if-else语句或Switch?特别是它总能取代if-else?我在循环中使用的大多数if-thens都是算术比较。这个问题产生于此问题。
How can polymorphism replace an if-else statement or Switch inside of a loop? In particular can it always replace an if-else? Most of the if-thens I use inside of loops are arithmetic comparisons. This question is spawned from this question.
int x;
int y;
int z;
while (x > y)
{
if (x < z)
{
x = z;
}
}
如何使用多态?
注意:我用Java编写了这个,但对任何OOL都感兴趣。
How would this work with polymorphism?
NOTE: I wrote this in Java but am interested in this for any OOL.
推荐答案
多态性通常会替换switch语句每种情况对应一种不同的类型。因此,而不是:
Polymorphism usually replaces switch statements when each case corresponds to a different type. So instead of having:
public class Operator
{
string operation;
public int Execute(int x, int y)
{
switch(operation)
{
case "Add":
return x + y;
case "Subtract":
return x - y;
case "Multiply":
return x * y;
case "Divide":
return x / y;
default:
throw new InvalidOperationException("Unsupported operation");
}
}
}
你有:
public abstract class Operator
{
public abstract int Execute(int x, int y);
}
public class Add : Operator
{
public override int Execute(int x, int y)
{
return x + y;
}
}
// etc
但是,对于您提供的比较类型的决策,多态性确实无济于事。
However, for the comparison type of decision you provided, polymorphism really doesn't help.
这篇关于多态如何替换循环内的if-else语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!