什么时候应该使用instanceof? [英] When should and shouldn't instanceof be used?

查看:78
本文介绍了什么时候应该使用instanceof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过各种文章,但我仍然不知道为什么不应该使用 instanceof .请让我知道您的想法.

I have gone through various articles, but I still do not know why instanceof should not be used. Kindly let me know your thoughts.

推荐答案

我发现有必要在错误的设计中使用instanceof提示.可以肯定的是,将会出现大型,复杂的开关风格的构造.我看到的其他大多数情况下,应该使用多态而不是instanceof.请参阅策略模式.(相关使用示例)

I find a need to use instanceof hints at bad design. It's a sure sign that a big, complex switch-style construct will follow. Most other times I see it used, we should use polymorphism rather than instanceof. See the Strategy pattern. (relevant examples of use)

我唯一需要使用它的是在实现 equals(Object o)时.

The only time I find I need to use it is when implementing equals(Object o).

这篇关于什么时候应该使用instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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