假设我们有以下代码块:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
所有的类型转换使代码看起来很难看,有没有办法在该代码块内将“事物”声明为 ObjectType?我知道我能做到
OjectType differentThing = (ObjectType)thing;
并从那时起使用“不同的东西”,但这会给代码带来一些混乱。有没有更好的方法来做到这一点,可能是这样的
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
我很确定这个问题过去曾被问过,但我找不到。请随时指出可能的重复项。