2016-10-27 34 views
-2

當我運行這段代碼,我得到的錯誤:System.InvalidCastException

An unhandled exception of type 'System.InvalidCastException' occurred in @override.exe Additional information: Unable to cast object of type 'animals.Animal' to type 'animals.dog'.

class Animal 
{ 
    public string name = "sdsfsdf"; 
    public virtual void bark() { 
     Console.WriteLine("woohhoo"); 
    } 
} 

class Dog : Animal 
{ 
    public int id = 11;   
    public override void bark() 
    { 
     Console.WriteLine("woof"); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Animal a = new Animal();  
     //bark; 
     a.bark(); 

     Dog d = new Dog(); 
     d.bark(); 

     // take out the virtual and override keyword infront of the method bark and see the difference*/ 

     Animal z = new Dog(); 
     z.bark(); 

     Console.WriteLine(z.name); 

     Dog f = (Dog) new Animal(); 
     f.bark(); 

     Console.ReadKey();    
    } 
} 
+3

爲什麼你認爲一個'Animal'是'Dog'? – SLaks

回答

2

因爲Animal不是Dog你不能做這個轉換。

然而,DogAnimal所以你可以做:

Animal a = (Animal) new Dog(); 
相關問題