using System;namespace InterfacesExample
{// 定义接口public interface INBAPlayable{void KouLan();}public interface ISupermanable{void Fly();}// 基类public class Person{public void CHLSS(){Console.WriteLine("人类吃喝拉撒睡");}}// Student 类实现多个接口public class Student : Person, INBAPlayable, ISupermanable{public void KouLan(){Console.WriteLine("学生可以扣篮");}public void Fly(){Console.WriteLine("学生会飞");}public void Study(){// 示例方法}}// teacher 类实现多个接口public class Teacher : INBAPlayable, ISupermanable{public void Fly(){Console.WriteLine("教师会飞");}public void KouLan(){Console.WriteLine("教师会扣篮");}}class Program{static void Main(string[] args){INBAPlayable nBA = new Student();nBA.KouLan();INBAPlayable nBA1 = new Teacher();nBA1.KouLan();Person p = new Student();p.CHLSS();Console.ReadKey();}}
}
代码分析
- 接口定义:
iNBAPlayable
接口定义了一个方法 KouLan()
。iSupermanable
接口定义了一个方法 Fly()
。
- 类实现:
Student
类继承自 Person
类,并实现了 iNBAPlayable
和 iSupermanable
接口。teacher
类实现了 iNBAPlayable
和 iSupermanable
接口。
- 多态性:
- 在
Main
方法中,iNBAPlayable
接口类型的变量 nBA
和 nBA1
分别被赋值为 Student
和 teacher
类的实例。通过接口调用 KouLan()
方法,展示了多态性。