是否可以在switch语句中使用instanceof运算符? [英] Is it possible to use the instanceof operator in a switch statement?

查看:194
本文介绍了是否可以在switch语句中使用instanceof运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用instanceof对象的开关盒有疑问:

I have a question of using switch case for instanceof object:

例如:我的问题可以用Java复制:

For example: my problem can be reproduced in Java:

if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():

如何使用switch...case实施?

推荐答案

这是子类型多态性有帮助的典型方案.执行以下操作

This is a typical scenario where subtype polymorphism helps. Do the following

interface I {
  void do();
}

class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }

然后,您可以简单地在this上调用do().

Then you can simply call do() on this.

如果您不能随意更改ABC,则可以应用访问者模式来实现相同的目的.

If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same.

这篇关于是否可以在switch语句中使用instanceof运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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