关于多态的一个小疑惑

amespace Inheritance
{
    public abstract class Animal
    {
        public string type="animal";
        public abstract void ShowType();
    }

    public class Bird : Animal
    {
        public string type = "Bird";
        public override void ShowType()
        {
            Console.WriteLine("Type is {0}", type);
        }
    }
    public class TestInheritance
    {
        public static void Main()
        {

            Animal animal = new Bird();
            Console.WriteLine("Type value is {0}", animal.type);
            animal.ShowType();
            Console.ReadKey();
        }
    }

}

程序输出的结果是:

Type value is animal

Type is Bird

为什么同样是将Bird类型赋给Animal,调用animal.ShowType()时用的是Bird的ShowType()方法,而调用animal.type的值却又是Animal里的type值?



哔哔one
浏览 548回答 2
2回答

翻过高山走不出你

因为Animal的type变量和Bird的type变量是不同的东西,且成员变量不支持多态性因此你访问animal.type的时候没有多态性,使用了Animal类的而调用ShowType方法的时候,因为是在Bird类内部,此时Bird类的type更接近调用的方法,所以使用了"Bird"
打开App,查看更多内容
随时随地看视频慕课网APP