2016-10-27 3 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

AnimalDogではないため、このキャストを行うことはできません。

しかし、Dogはそうあなたが行うことができますAnimal次のとおりです。

Animal a = (Animal) new Dog(); 
関連する問題