-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();
}
}
爲什麼你認爲一個'Animal'是'Dog'? – SLaks