一、如何用接口实现多态?
1.定义一个接口。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { public interface people //定义一个接口People { void SayHi(); //定义一个SayHi方法 } }
2.创建两个类Student.c和Teacher.cs继承接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { class Student:people //继承接口Peoper { public void SayHi() { Console.WriteLine("你好我是学生"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 继承之抽象类 { class Teacher:people //继承接口Peoper { public void SayHi() { Console.WriteLine("你好我是老师"); } } }
3.创建一个program.cs类用来输出结果
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(); } } }
输出结果: