多态如何替换循环内的

多态如何替换循环内的

本文介绍了多态如何替换循环内的 if-else 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多态性如何替换循环内的 if-else 语句或 Switch?特别是它总是可以代替 if-else 吗?我在循环中使用的大多数 if-then 都是算术比较.这个问题源于这个 问题.

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.

推荐答案

当每个 case 对应于不同的类型时,多态通常会替换 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 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:52