的比方說,我們有下面的代碼塊:聲明變量是某種類型的
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();
}
我很確定這個問題已被問過去,我找不到它。隨意指點我可能的重複。
我不認爲除了你提到的方式外,還有別的辦法。 – nhahtdh