1.多态指的是多种表现形态。同一段代码,不同的对象调用会有不同的执行效果。
2.实现多态的三种手段。
- 使用virtual
Job[] js = new Job[3];
js[0] = new Teacher();
js[1] = new Student();
js[2] = new SchoolMaster();
for (int i = 0; i < js.Length; i++)
{
if (js[i] != null)
{
js[i].SayContent();//这段代码即实现了多态
}
}
使用abstract
class Program { static void Main(string[] args) { Job[] js = new Job[3]; js[0] = new Teacher(); js[1] = new Student(); js[2] = new Nurse(); for (int i = 0; i < js.Length; i++) { if (js[i] != null) { js[i].WorkContent(); } } Console.ReadKey(); } } public abstract class Job { public string Name { get; set; } public double Money { get; set; } public abstract void WorkContent(); } class Teacher : Job { public override void WorkContent() { Console.WriteLine("教书育人"); } } class Student : Job { public override void WorkContent() { Console.WriteLine("学习"); } } class Nurse : Job { public override void WorkContent() { Console.WriteLine("治疗"); } }
- 使用接口interface
class Program { static void Main(string[] args) { //Person p = new Student2(); //ReleaseSkills(p); ISkill[] skills = new ISkill[3]; skills[0] = new Student1(); skills[1] = new Student2(); skills[2] = new Zero(); for (int i = 0; i < skills.Length; i++) { ReleaseSkills(skills[i]); } Console.ReadKey(); } static void ReleaseSkills(ISkill i) { i.Skill(); } } public abstract class Person:ISkill { private string name; private int age; public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public abstract void Skill();//抽象类可以交给子类去实现 } class Student1 : Person { public Student1() { this.Name = "辰月"; } public override void Skill() { Console.WriteLine("{0}:天乾蝶舞",this.Name); } } class Student2 : Person { public Student2() { this.Name = "辗迟"; } public override void Skill() { Console.WriteLine("{0}:火离耀月",this.Name); } } /// <summary> /// Tips:零并不是继承自人。这是两种类型的生物。所以当类型不一样的时候我们可以考虑用接口 /// </summary> class Zero : ISkill { private string name; public Zero() { this.name = "零"; } public string Name { get { return name; } set { name = value; } } public void Skill() { Console.WriteLine("{0}:零煞",this.Name); } } interface ISkill { void Skill(); }