using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { class Program { static void Main(string[] args) { //定义接口数组 IFlyable [] flys= {new Sparrow(),new Eagle(),new Swan ()}; foreach (IFlyable outFlys in flys ){ outFlys.Fly(); } Console.ReadKey (); } } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { //基类 //老鹰 麻雀 会飞 但鸵鸟 不会飞 飞的方法不合适放在基类中 飞的方法如果放在子类中也需要每个重写也麻烦 需要定义个接口 让 /老鹰 麻雀 继承这个接口 abstract class Brid { //public void Write() { // Console.WriteLine("我是鸟类"); //} //abstract 抽象 派生类中需重写 override public abstract void Eat(); } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { //继承 Brid 类 与IFlyable接口 class Eagle : Brid, IFlyable { public override void Eat() { Console.WriteLine("我是老鹰专吃小鸡"); } //接口的实现需要在实现接口的类中进行实现 public void Fly() { Console.WriteLine("我是老鹰我会飞"); } } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { // 接口的声明 interface IEatable { //接口的成员可以是方法 属性 事件和索引器,但不能包含常数 字段 运算符 实例构造函数 析构函数,也不能包括任何种类的静态成员 //接口不能包含字段 //接口成员不允许添加访问修饰符,默认public ,成员也不能加 abstract(抽象)访问修饰符 //接口不能包含实现其成员的任何代码,而只能定义成员本身() //实现过程必须在实现接口的类中完成 //属性 //接口中不能有访问修饰符 string _name { get; set; } //方法 void Write(); string Read(); string Ifly(); } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { interface IFlyable { //接口的成员可以是方法 属性 事件和索引器,但不能包含常数 字段 运算符 实例构造函数 析构函数,也不能包括任何种类的静态成员 //接口不能包含字段 //接口成员不允许添加访问修饰符,默认public ,成员也不能加 abstract(抽象)访问修饰符 //接口不能包含实现其成员的任何代码,而只能定义成员本身() //实现过程必须在实现接口的类中完成 //属性 //接口中不能有访问修饰符 void Fly(); } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { class Ostrich : Brid { public override void Eat() { Console.WriteLine("我是鸵鸟,我专吃青草"); } } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { class Sparrow : Brid, IFlyable { public override void Eat() { Console.WriteLine("我是麻雀专吃粮食"); } //接口的实现需要在实现接口的类中进行实现 public void Fly() { Console.WriteLine("我是麻雀我会飞"); } } } using System; using System.Collections.Generic; using System.Text; namespace V6._接口的声明 { // 天鹅能吃 也能飞 继承 基类Brid 接口IFlyable class Swan : Brid, IFlyable { public override void Eat() { Console.WriteLine("我是天鹅,我专吃鱼"); } public void Fly() { Console.WriteLine("我是天鹅,我会飞"); } } } |
|
来自: 时间剧毒 > 《第十章:接口、抽象与密封》