接口,是一种协议规范,其中的属性、方法等成员只能定义,不能做其他操作。
接口中的成员,默认public,因此,成员无修饰符。
【格式】修饰符 interface 接口名称:接口列表{ 接口内容; }
通过类的继承来实现接口(成员的功能)。
namespace ConsoleApplication1 { interface Student //接口 { string Name { get; set; } //只能定义 } class Boy:Student //类继承,实现接口 { string name; public string Name //成员功能:等待赋值 { get { return name; } set { name = value; } } } class Program { static void Main(string[] args) { Boy b = new Boy(); b.Name = "张三"; //赋值 Console.WriteLine(b.Name); } } }
接口成员的显示实现:如果接口列表的成员相同,那么在定义成员功能时会发生混淆
接口名.成员,来定义具体的功能。
namespace ConsoleApplication1 { interface Student //接口1 { string Name { get; set; } } interface Student2 //接口2,成员与接口1相同 { string Name { get; set; } } class Boy:Student,Student2 //继承了两个接口 { string name; string Student.Name //接口名.成员 { get { return name; } set { name = value; } } string Student2.Name //接口名.成员 { get { return name; } set { name = value; } } } class Program { static void Main(string[] args) { Student s = new Boy(); //显示的引用方式 Student2 s2 = new Boy(); s.Name = "接口一"; s2.Name = "接口二"; Console.WriteLine(s.Name+ s2.Name); } } }
接口的显式、隐式实现,参考https://www.cnblogs.com/liuxiaopi/p/6484026.html