接口:用来约束所有的子类的一系列规范,一个类可以实现多个接口。
【注意事项】
1、接口中的方法不是抽象方法。
2、接口中的方法不能有访问权限修饰符。
3、实现接口方法的时候注意事项:接口中的方法必须实现为public权限。实现接口方法不能使用override。抽象类实现接口可以把接口方法实现为抽象方法。接口方法可以实现为虚方法。如果一个类既有继承,也有接口,接口一定在父类之后。
4、接口的命名有命名规范,以I开头。
//定义一个接口
interface IUSB
{
void Charge();//充电
void TransportData();//数据传输
}
class Hradware{}
abstract class Keyboard : IUSB
{
public abstract void Charge();
public abstract void TransportData();
}
//让一个类去实现接口
class Mouse : Hradware, IUSB
{
//被实现虚方法
public virtual void Charge() { }
public void TransportData() { }
}
}
【练习】小明雇保姆案例
/*
* 小明请保姆练习
*/
//家政服务规范
interface IHouseWorkService
{
void Wash();
void Cook();
void Clean();
}
//照顾人服务规范
interface ITakeCareService
{
void Cook();
void WarmBed();
}
//人实体
class Person
{
public string name;
//小明让保姆去洗衣服方法
public void LetDo()
{
IHouseWorkService i = new Robot();//向上转型:由实现类类型转型为接口类型
Robot r = i as Robot;//向下转型
if (i is Robot)
{
Robot r1 = i as Robot;
}
}
//参数可以这么写
public void LetDo1(IHouseWorkService s)
{
s.Wash();
}
}
//保姆实体
class Nurse : Person, IHouseWorkService
{
public void Wash() { Console.WriteLine(name + "在洗衣服"); }
public void Cook() { Console.WriteLine(name + "在做饭"); }
public void Clean() { Console.WriteLine(name + "在打扫房间"); }
}
//机器人实体
class Robot : IHouseWorkService
{
public void Wash() { Console.WriteLine("机器人在洗衣服"); }
public void Cook() { Console.WriteLine("机器人在做饭"); }
public void Clean() { Console.WriteLine("机器人在打扫房间"); }
}
class GirlFriend : Person, IHouseWorkService, ITakeCareService
{
public void Wash() { }
public void Cook() { }
public void Clean() { }
public void WarmBed() { }
}
【练习】小明寄快递
/*
* 【练习】小明需要寄一个包裹
*
* 顺丰:空运、陆运
* 韵达:陆运
* EMS:空运
*/
public interface ITransportonAir
{
//发空运
void TransportOnAir();
}
public interface ITransportOnLand
{
//发陆运
void TransportOnLand();
}
public class ShunFeng : ITransportonAir, ITransportOnLand
{
public void TransportOnLand()
{
Console.WriteLine("顺丰快递在陆运");
}
public void TransportOnAir()
{
Console.WriteLine("顺丰快递在空运");
}
}
public class YunDa:ITransportOnLand
{
public void TransportOnLand()
{
Console.WriteLine("韵达快递在陆运");
}
}
public class EMS :ITransportonAir
{
public void TransportOnAir()
{
Console.WriteLine("EMS快递在空运");
}
}
public class Person
{
//发陆运
public void SendPackageOnLand(ITransportOnLand Land)
{
Land.TransportOnLand();
}
//发空运
public void SendPackageOnAir(ITransportonAir Air)
{
Air.TransportOnAir();
}
}
【练习】接口约束属性
public interface IStupid {
//接口中还可以写属性
//实现类中需要有一个属性叫做Age,并提供set和get访问器
int Age { set; get; }
string Name { get; }
}
public class Hashiqi : IStupid
{
public int Age
{
set { }
get { return 1; }
}
public string Name
{
get { return "哈士奇"; }
}
}
【练习】接口的继承
interface IHouseWorkService
{
void Wash();
}
interface ITakeCareService
{
void WarmBed();
}
//接口也有继承,并且接口之间的继承是多继承
interface IGrilFriendService : IHouseWorkService, ITakeCareService
{
//这个接口中拥有 IHouseWorkService, ITakeCareService中的所有的方法
}
class Person : IGrilFriendService
{
public void WarmBed(){}
public void Wash(){}
}