System.InvalidCastException

时间:2016-10-27 23:23:35

标签: c#

当我运行此代码时,我收到错误:

  

未处理的类型' System.InvalidCastException'发生在@ override.exe中   附加信息:无法施放类型动物的物体。动物'键入' 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();               
    }
}

1 个答案:

答案 0 :(得分:2)

您无法执行此投射,因为Animal不是Dog

但是,DogAnimal所以你可以这样做:

Animal a = (Animal) new Dog();