多态性如何替换循环内的 if-else 语句? [英] How can Polymorphism replace an if-else statement inside of a loop?

查看:33
本文介绍了多态性如何替换循环内的 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 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆