using System;
namespace 父类子类
{
class Person
{
public Person()
{
Console.WriteLine("我是父类构造函数");
}
public virtual void SayHello()
{
Console.WriteLine("父类SayHello");
}
}
class Son : Person
{
public Son()
{
Console.WriteLine("我是子类构造函数");
}
public override void SayHello()
{
Console.WriteLine("子类SayHello");
}
}
class Program
{
static void Main(string[] args)
{
Person p1 = new Person();
p1.SayHello();
Console.WriteLine("===============================");
Son s1 = new Son();
s1.SayHello();
Console.WriteLine("===============================");
Person p2 = new Son();
p2.SayHello();
Console.WriteLine("===============================");
Son s2 = new Son();
Person ps2 = (Person)s2;
ps2.SayHello();
Console.WriteLine("===============================");
Person p3 = new Son();
Son s3 = (Son)p3;
s3.SayHello();
Console.WriteLine("===============================");
Person p4 = new Person();
Son s4 = (Son)p4; //报错!
s4.SayHello();
}
}
}
运行结果如下: