7

假设我们有以下代码块:

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();
}

我很确定这个问题过去曾被问过,但我找不到。请随时指出可能的重复项。

4

3 回答 3

9

不,一旦声明了变量,该变量的类型就固定了。我相信更改变量的类型(可能是暂时的)会带来以下更多的混乱:

ObjectType differentThing = (ObjectType)thing;

您认为令人困惑的方法。这种方法被广泛使用和惯用 - 当然,在所有需要它的地方。(这通常有点代码味道。)

另一种选择是提取方法:

if (thing instanceof ObjectType) {
    performOperations((ObjectType) thing);
}
...

private void performOperations(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}
于 2012-06-25T09:41:22.677 回答
4

一旦声明了一个变量,它的类型就不能改变。你的differentThing方法是正确的:

if (thing instanceof ObjectType) {
    OjectType differentThing = (ObjectType)thing;
    differentThing.operation1();
    differentThing.operation2();
    differentThing.operation3();
}

我也不会说它令人困惑:只要differentThing变量的范围仅限于if运算符的主体,读者就很清楚发生了什么。

于 2012-06-25T09:41:24.640 回答
2

可悲的是,这是不可能的。

原因是此范围内的“事物”将始终具有相同的对象类型,并且您无法在代码块中对其进行重铸。

如果你不喜欢有两个变量名(比如 thing 和 castedThing),你总是可以创建另一个函数;

if (thing instanceof ObjectType) {
    processObjectType((ObjectType)thing);
}
..

private void processObjectType(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}
于 2012-06-25T09:46:05.337 回答