System.InvalidCastException
本文关键字:InvalidCastException System | 更新日期: 2023-09-27 18:15:23
当我运行这段代码时,我得到了错误:
类型为"System"的未处理异常。在@override.exe中发生InvalidCastException附加信息:无法施放"动物"类型的对象。输入"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();
}
}
不能这样强制转换,因为Animal
不是Dog
。
然而,Dog
是一个Animal
,所以你可以这样做:
Animal a = (Animal) new Dog();