当我运行此代码时,我收到错误:
未处理的类型' 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();
}
}
答案 0 :(得分:2)
您无法执行此投射,因为Animal
不是Dog
。
但是,Dog
是Animal
所以你可以这样做:
Animal a = (Animal) new Dog();