是什么原因导致以下垂头丧气的失败?

时间:2019-06-24 16:06:11

标签: c#

我试图将Animal强制转换为Dog,但失败。是什么原因导致此失败?

class Animal
{
    private readonly string name;
    public Animal(string name) => this.name = name;
    public virtual string Greet() => $"Animal's {name}";
}

class Dog : Animal
{
    public Dog(string name) : base(name) { }
    public override string Greet() => $"Dog's {base.Greet()}";
}

class Program
{
    static void Main()
    {
        Animal a = new Animal("Hello World");
        Dog d = a as Dog;

        if (d == null)
            Console.WriteLine("Cast failed.");
        else
            Console.WriteLine(d.Greet());
    }
}

1 个答案:

答案 0 :(得分:3)

因为a是动物而不是狗。您实例化了一只动物。

以下将起作用(创建狗实例而不是动物):

class Program
{
    static void Main()
    {
        Animal a = new Dog("Hello World");
        Dog d = a as Dog;

        if (d == null)
            Console.WriteLine("Cast failed.");
        else
            Console.WriteLine(d.Greet());
    }
}