是否可以在 switch 语句中使用 instanceof 运算符? [英] Is it possible to use the instanceof operator in a switch statement?
本文介绍了是否可以在 switch 语句中使用 instanceof 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于 instanceof
对象使用 switch case 的问题:
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
.
如果您不能随意更改A
、B
和C
,您可以应用访问者模式来实现相同的效果.
If you are not free to change A
, B
, and C
, you could apply the visitor pattern to achieve the same.
这篇关于是否可以在 switch 语句中使用 instanceof 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文