关于.net的一个继承的问题
- C# code
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();
[解决办法]
bird2这个变量的类型是Bird,但是它指向了一个Chichen的对象。
ShowType又是一个虚函数,调用谁的ShowType由对象实例的类型决定,而不是变量的类型决定
[解决办法]
虽然使用bird声明的 但是实例化为什么就是什么 bird2 虽然是bird的类型 但是是用Chicken开辟的空间 那么空间中必然有ShowType()方法和 private string type = "Chicken"属性