现要求在一个静态方法中,他的形参是Person
p,实参可能是Student类或者是Teacher类,在函数内部通过调用p.SayHi()来达到调用其不同子类的不同SayHi方法。
通过接口
public interface IPerson
{
void SayHi();
}
class Student : IPerson
{
public void SayHi()
{
Console.WriteLine(“我是Student类中的SayHi方法”);
}
}
通过虚方法实现多态的完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 多态的实现
{
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
Teacher tea = new Teacher();
Fun(stu);
Fun(tea);
Console.ReadKey();
}
static void Fun(Person p)
{
p.SayHi();
}
}
class Person
{
public virtual void SayHi()
{
Console.WriteLine("我是Person类中的SayHi方法");
}
}
class Student : Person
{
public override void SayHi()
{
Console.WriteLine("我是Student类中的SayHi方法");
}
}
class Teacher : Person
{
public override void SayHi()
{
Console.WriteLine("我是Teacher类中的SayHi方法");
}
}
}