using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 接口
{
public interface IFlyable
{
void liftoff();
}
public class Bird:IFlyable
{
public virtual void liftoff()
{
Console.WriteLine("Bird has lift off!!");
}
}
public class Superman:IFlyable
{
public void liftoff()
{
Console.WriteLine("Superman has lift off!!");
}
}
public class Sparrow : Bird
{
public override void liftoff()
{
Console.WriteLine("Sparrow has lift off!!");
}
}
public abstract class Ufo:IFlyable //抽象类的存在只为被继承 抽象方法只允许在抽象类中定义而且不能在其中被实现
{
public virtual void liftoff()
{
Console.WriteLine("UFO has lift off!");
}
}
public class MarsUfo : Ufo
{
public override void liftoff()
{
Console.WriteLine("UFO take-off from Mars");
}
}
public class Car
{
}
public class TestInterface1
{
public static void Test1()
{
//IFlyable fly = new IFlyable();//flase 无法创建接口的实例 但如果new的是 Superman类 的话则编译能通过(其它非实现该接口的类均不可以)
IFlyable fly = new Superman(); //该类实例化了这个接口 故可以把它当接口来使用
fly.liftoff(); //这跟类实例化对象不同 类拥有的方法他不一定有 而接口有点类的实例一定有 接口关心的是“合同”里面的内容
fly = null; // 这样子做比较安全 目的跟c++ 不声明为初始化的指针一样 为了安起见
fly=new Bird (); //指向 鸟
fly.liftoff(); //多态
Console.WriteLine("--------------------");
}
public static void Test2()
{
//接口允许派生类使用
IFlyable fly=new Bird();
fly = new Sparrow();
fly.liftoff();
Console.WriteLine("-----------------------");
}
public static void Test3()
{
//IFlyable fly=new Ufo (); //抽象类不能 当作接口 抽象类无法创建对象
Ufo ufo = new MarsUfo(); //抽象父类 实例子类是可以的
IFlyable fly = ufo; //可以被抽象类的子类实现
fly.liftoff();
}
public static void Test4()
{
Superman obj1 = new Superman();
//UseInterface(obj1 );
Bird obj2 = new Sparrow();
//UseInterface(obj2);
Car obj3 = new Car();
//UseInterface(obj3);//不是接口
UseInterface2(obj1 );
UseInterface2(obj3);
}
public static void UseInterface(IFlyable fly)
{
fly.liftoff();
}
public static void UseInterface2(object obj)
{
//if (obj is IFlyable )
//{
// IFlyable fly = (IFlyable)obj;
// fly.liftoff();
//}
//else
//{
// Console.WriteLine("{0}没有实现接口",obj);
//}
IFlyable fly=null;
fly=obj as IFlyable;//IFlyable fly=obj as IFlyable
if (fly==null)
{
Console.WriteLine("转换失败");
}
else
{
fly.liftoff();
}
}
}
}