[英]Declaring variable to be of certain type
假设我们有以下代码块:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
所有类型转换使代码看起来很难看,有没有办法在代码块中声明'thing'作为ObjectType? 我知道我能做到
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.