想想這樣,您可以將程序強制轉換爲測試,因爲程序是測試。
您不能將測試轉換爲程序,因爲測試不是程序。
向下傾倒是安全的,只有在確定該類型的對象是安全的時候纔可以向上傾倒。
需要上傳通常是一種代碼氣味,如果您發現您經常需要上傳您的對象,那麼您的設計可能有問題。
希望這有助於
編輯:是否總是安全的向下轉換?
downcasting的行爲是根據定義 - 根據我 - 在哪裏你知道對象的類型,而你把它放在更低的繼承樹下。例如 貓和狗都繼承了動物,橡樹和樺木都從樹繼承。
它始終是安全的做到這一點
public void DoThingWithCat(Cat snuggles)
{
snuggles.Meow();
DoThingWithAnimal(snuggles); // this is always OK, because we know
// the type of snuggles, and we know
// snuggles is an animal
}
這是一個上溯造型。這樣做是不安全的,這也是一個代碼是一種代碼異味,如果你需要這樣做,你的對象層次結構可能有問題。
public void DoSomethingElse(Animal anAnimal)
{
DoThingWithCat(anAnimal); // this is NOT always OK, because we
// DO NOT know the type of anAnimal,
// and it may not be a Cat
}
這也是不安全的,因爲它是直接鑄造,不一定向上鑄造或向下鑄造
public void DoSomethingDifferent(object anObject)
{
DoThingWithAnimal(anObject); // this may or may not work,
// depending on the type passed in,
// this is a recipe for disaster,
// because may not be an Animal,
// it could be a Tree.
}
這是令人困惑,因爲強制轉換,既可以指「使給定類型的新的東西出來的這個老東西」,而相反的,「檢查給定的事情是否真的給定類型的」。有關此主題的更多思考,請參閱http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx。 – 2009-06-18 14:11:12