一、虚方法实现多态
1,创建一个people基类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { public class people { public virtual void SayHi()//定义一个SayHi的虚方法 { } } }
2.创建两个子类Student.cs和Teacher.cs继承基类people
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { class Student : people { public override void SayHi() //重写 { Console.WriteLine("你好我是学生"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { class Teacher:people //继承Peoper类 { public override void SayHi() //重写 { Console.WriteLine("你好我是老师"); } } }
输出结果:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { class Program { static List<people> peopers = new List<people>(); //定义一个泛型实例 public static void InitData() { Student st = new Student(); Teacher tc = new Teacher(); peopers.Add(st); peopers.Add(tc); } public static void Start() { foreach (people peoper in peopers) //遍历泛型实例 { peoper.SayHi(); } } static void Main(string[] args) { InitData(); Start(); Console.ReadLine(); } } }

本文通过创建基类people及其子类Student和Teacher,演示了C#中虚方法和多态性的实现方式。利用泛型集合存储不同类型的对象,并通过基类引用调用虚方法,展示了多态的特性。
892

被折叠的 条评论
为什么被折叠?



