[英]Declaring variable to be of certain type
Let's say we have the following block of code: 假设我们有以下代码块:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
All the typecasting makes the code look ugly, is there a way of declaring 'thing' as ObjectType inside that block of code? 所有类型转换使代码看起来很难看,有没有办法在代码块中声明'thing'作为ObjectType? I know I could do
我知道我能做到
OjectType differentThing = (ObjectType)thing;
and work with 'differentThing' from then on, but that brings some confusion to the code. 从那时起开始使用'differentThing',但这会给代码带来一些困惑。 Is there a nicer way of doing this, possibly something like
有没有更好的方法来做到这一点,可能是这样的
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
I am pretty sure this question has been asked in the past, I couldn't find it though. 我很确定过去曾问过这个问题,但我找不到它。 Feel free to point me to the possible duplicate.
请随意指出可能的重复。
No, once a variable is declared, the type of that variable is fixed. 不,一旦声明了变量,该变量的类型就是固定的。 I believe that changing the type of a variable (potentially temporarily) would bring far more confusion than the:
我认为,改变变量的类型(可能是暂时的)会带来更混乱比:
ObjectType differentThing = (ObjectType)thing;
approach you believe to be confusing. 接近你认为是混乱的。 This approach is widely used and idiomatic - where it's required at all, of course.
这种方法被广泛使用和惯用 - 当然,它是必需的。 (This is typically a bit of a code smell.)
(这通常有点代码味道。)
Another option is to extract a method: 另一种选择是提取方法:
if (thing instanceof ObjectType) {
performOperations((ObjectType) thing);
}
...
private void performOperations(ObjectType thing) {
thing.operation1();
thing.operation2();
thing.operation3();
}
Once a variable is declared, it's type cannot change. 一旦声明了变量,它的类型就不会改变。 Your
differentThing
approach is the correct one: 您的
differentThing
方法是正确的:
if (thing instanceof ObjectType) {
OjectType differentThing = (ObjectType)thing;
differentThing.operation1();
differentThing.operation2();
differentThing.operation3();
}
I wouldn't call it confusing, either: as long as the scope of the differentThing
variable is limited to the body of the if
operator, it is clear to the readers what is going on. 我也不会把它称为混淆:只要
differentThing
变量范围仅限于if
运算符的主体,读者就会明白发生了什么。
Sadly, this is not possible. 可悲的是,这是不可能的。
The reason is that "thing" in this scope will always be of the same object type, and you cannot recast it within a block of code. 原因是此范围中的“thing”将始终具有相同的对象类型,并且您无法在代码块中重新创建它。
If you dislike having two variable names (like thing and castedThing), you could always create another function; 如果你不喜欢有两个变量名(比如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.