2010-12-22 74 views
1

我猜想一個基本問題的位,但如果我想要一個對象擁有另一個類型爲A或B的對象,那麼使用該對象的應用程序如何訪問特定的屬性?例如。訪問抽象對象上的具體屬性?

public abstract class Animal 
{ 
    private int Age; 
    // Get Set 
} 

public class Tiger: Animal 
{ 
    private int NoStripes; 
    // Get Set 
} 

public class Lion : Animal 
{ 
    private bool HasMane; 
    // Get Set 
} 

public class Zoo 
{ 
    private Animal animal; 
    // Get Set 
} 

public static void Main() 
{ 
    Zoo zoo = new Zoo(); 
    zoo.animal = new Tiger(); 

    // want to set Tiger.NoStripes 
} 

回答

0

這是遺傳和多態性的要旨。

如果你能夠確定動物的一個實例實際上虎的一個實例,你可以將它轉換:

((Tiger)zoo.Animal).NoStripes = 1; 

但是,如果你試圖做這樣做對ISN動物的一個實例Tiger,你會得到一個運行時異常。

例如:

Zoo zoo = new Zoo(); 
zoo.animal = new Tiger(); 
((Tiger)zoo.Animal).NoStripes = 1; //Works Fine 

((Lion)zoo.Animal).NoStripes = 1; //!Boom - The compiler allows this, but at runtime it will fail. 

有是使用替代鑄造語法「爲」關鍵字,如果轉換失敗,它返回而不是例外情況爲空。這聽起來不錯,但在實踐中,當空對象被佔用時,你很可能會在稍後得到微妙的錯誤。

Tiger temp = zoo.Animal as Tiger; //This will not throw an exception 
temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug 
zoo.Animal = temp; 

爲了避免空引用異常,可以空,當然檢查

Tiger temp = zoo.Animal as Tiger; //This will not throw an exception 
if (temp != null) 
{ 
    temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug 
    zoo.Animal = temp; 
} 
2

你將不得不投​​到Tiger

或者你可以嘗試像

public abstract class Animal 
{ 
    public int Age; 
    // Get Set 
} 

public class Tiger : Animal 
{ 
    public int NoStripes; 
    // Get Set 
} 

public class Lion : Animal 
{ 
    public bool HasMane; 
    // Get Set 
} 

public class Zoo<T> where T : Animal 
{ 
    public T animal; 
    // Get Set 
} 

Zoo<Tiger> zoo = new Zoo<Tiger>(); 
zoo.animal = new Tiger(); 
zoo.animal.NoStripes = 1; 
0

直接的答案是做

public static void Main() { 
    Zoo zoo = new Zoo(); 
    zoo.animal = new Tiger(); 

    ((Tiger)zoo.Animal).NoStripes = 10; 
} 

當然對於這工作你需要知道​​實際上是一個Tiger。您可以使用zoo.Animal is Tiger進行測試(儘管as運營商優於is)。

但是,一般來說,像這樣設計你的程序並不是很好。您可能需要編寫的代碼很可能很麻煩。

+0

同意了,所以怎麼去解決呢?如果您的對象包含/或,例如車庫有A車或B車,那麼最好的設計方法是什麼?在包含對象中創建A和B似乎也是錯誤的... – DAE 2010-12-22 14:17:07