using System;
using System.Data;public abstract class Animal
{
    public abstract void ShowType();    public void Eat() 
    {
        Console.WriteLine("Animal always eat.");
    }
}public class Bird : Animal
{
    private string type = "Bird";    public override void ShowType()
    {
        Console.WriteLine("Type is {0}", type);
    }    private string color;    public string Color
    {
        get { return color; }
        set { color = value; }
    }
}public class Chicken : Bird
{
    private string type = "Chicken";
    
    public override void ShowType()
    {
        Console.WriteLine("Type is {0}", type);
    }
    
    public void ShowColor()
    {
        Console.WriteLine("Color is {0}", Color);
    }
}public class TestInheritance
{
    public static void Main()
    {
        Bird bird2 = new Chicken();
        bird2.ShowType();
    }
}
以上是一段关于C#继承的代码,运行的结果是Type is Chicken
但是添加监视发现bird2.type的值为Bird
想知道这是为什么,望高人指点,谢谢

解决方案 »

  1.   


    实例化的是Chicken
    Bird bird2 = new Chicken();
      

  2.   

    bird2这个变量的类型是Bird,但是它指向了一个Chichen的对象。
    ShowType又是一个虚函数,调用谁的ShowType由对象实例的类型决定,而不是变量的类型决定
      

  3.   

    showtype调用的type并非是bird.type。
    http://topic.csdn.net/u/20090116/11/960b32e0-4897-4ff0-ab9c-8de4335f7c1e.html
      

  4.   

    虽然使用bird声明的  但是实例化为什么就是什么  bird2  虽然是bird的类型  但是是用Chicken开辟的空间  那么空间中必然有ShowType()方法和 private string type = "Chicken"属性    
      

  5.   

    大家说的都很对啊,但是为什么在对象bird2创建后,bird2.type的值是bird呢?主要是这个不明白