声明变量是某种类型的
问题描述:
的比方说,我们有下面的代码块:声明变量是某种类型的
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
所有类型转换使得代码很难看,有没有宣布“东西”作为对象类型是块内的一种方式的代码?我知道我可以做
OjectType differentThing = (ObjectType)thing;
并从那以后使用'differentThing',但是这会给代码带来一些混淆。有没有更好的方式做到这一点,可能类似于
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
我很确定这个问题已被问过去,我找不到它。随意指点我可能的重复。
答
不,一旦变量被声明,那个变量的类型是固定的。我相信,改变一个变量(可能是暂时的)的类型会带来比远更多的困惑:你认为是混乱
ObjectType differentThing = (ObjectType)thing;
方法。这种方法被广泛使用和惯用 - 当然它是必需的。 (这通常是一个比特的码气味。)
另一种选择是提取物的方法:一旦一个变量被声明
if (thing instanceof ObjectType) {
performOperations((ObjectType) thing);
}
...
private void performOperations(ObjectType thing) {
thing.operation1();
thing.operation2();
thing.operation3();
}
答
,它的类型不能改变。你differentThing
的做法是正确的:
if (thing instanceof ObjectType) {
OjectType differentThing = (ObjectType)thing;
differentThing.operation1();
differentThing.operation2();
differentThing.operation3();
}
我不会把它混乱,无论是:只要differentThing
变量的范围仅限于if
操作者的身体,很明显,以飨读者到底是怎么回事。
答
不幸的是,这是不可能的。
原因是这个范围中的“thing”将始终是相同的对象类型,并且您不能在一段代码中重铸它。
如果你不喜欢有两个变量名(比如thing和castedThing),你总是可以创建另一个函数;
if (thing instanceof ObjectType) {
processObjectType((ObjectType)thing);
}
..
private void processObjectType(ObjectType thing) {
thing.operation1();
thing.operation2();
thing.operation3();
}
我不认为除了你提到的方式外,还有别的办法。 – nhahtdh