2012-06-25 124 views
7

的比方說,我們有下面的代碼塊:聲明變量是某種類型的

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

我很確定這個問題已被問過去,我找不到它。隨意指點我可能的重複。

+1

我不認爲除了你提到的方式外,還有別的辦法。 – nhahtdh

回答

9

不,一旦變量被聲明,那個變量的類型是固定的。我相信,改變一個變量(可能是暫時的)的類型會帶來比遠更多的困惑:你認爲是混亂

ObjectType differentThing = (ObjectType)thing; 

方法。這種方法被廣泛使用和慣用 - 當然它是必需的。 (這通常是一個比特的碼氣味。)

另一種選擇是提取物的方法:一旦一個變量被聲明

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

private void performOperations(ObjectType thing) { 
    thing.operation1(); 
    thing.operation2(); 
    thing.operation3(); 
} 
4

,它的類型不能改變。你differentThing的做法是正確的:

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

我不會把它混亂,無論是:只要differentThing變量的範圍僅限於if操作者的身體,很明顯,以饗讀者到底是怎麼回事。

2

不幸的是,這是不可能的。

原因是這個範圍中的「thing」將始終是相同的對象類型,並且您不能在一段代碼中重鑄它。

如果你不喜歡有兩個變量名(比如thing和castedThing),你總是可以創建另一個函數;

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

private void processObjectType(ObjectType thing) { 
    thing.operation1(); 
    thing.operation2(); 
    thing.operation3(); 
} 
相關問題