传智播客.net培训411种的多态继承练习

传智播客.net培训411类的多态继承练习
今天蒋坤老师讲了一道有关类的多态的练习题。梳理一下。
这里主要是父类中定义虚方法,子类中重写父方法
这题的关键是弄明白四个类的关系:
B继承了A,隐藏了A中的Show的方法,并且把show声明为虚方法
C继承了B,c中没有属性,重写了Show方法
D继承了C,隐藏了C中的show方法

class A
{
public string Str = "A";
public void Show() { Console.WriteLine("Show A"); }
}
class B : A
{
public string Str = "B";
public virtual void Show() { Console.WriteLine("Show B"); }
}
class C : B
{
public override void Show() { Console.WriteLine("Show C"); }
}
class D : C
{
public string Str = "D";
public void Show() { Console.WriteLine("Show D"); }
}
class Program
{
static void Main(string[] args)
{
D d = new D();
C c = d;
B b = d;
A a = d;
Console.WriteLine(d.Str);
Console.WriteLine(c.Str);
Console.WriteLine(b.Str);
Console.WriteLine(a.Str);
Console.WriteLine("------------");
d.Show();
c.Show();
b.Show();
a.Show();
Console.ReadLine();
}
}

首先弄明白四个类的关系:
B继承了A,隐藏了A中的Show的方法,并且把show声明为虚方法
C继承了B,c中没有属性,重写了Show方法
D继承了C,隐藏了C中的show方法

D d = new D();
C c = d;
B b = d;
A a = d;
Console.WriteLine(d.Str);
输出的是D
Console.WriteLine(c.Str);
因为c中没有str属性,c输出的是父类B中的属性B
Console.WriteLine(b.Str);
输出b
Console.WriteLine(a.Str);
输出a

---------------
d.Show();
输出D
c.Show();
输出C
b.Show();
C重写了B的show方法,这里于是输出C
a.Show();
输出A