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
想知道这是为什么,望高人指点,谢谢
实例化的是Chicken
Bird bird2 = new Chicken();
ShowType又是一个虚函数,调用谁的ShowType由对象实例的类型决定,而不是变量的类型决定
http://topic.csdn.net/u/20090116/11/960b32e0-4897-4ff0-ab9c-8de4335f7c1e.html