1.接口的定义
接口的定义是指定一组函数成员而不实现成员的引用类型,其它类型和接口可以继承接口。
2.接口的特点
(1)通过接口可以实现多重继承,C#接口的成员不能有public、protected、internal、private等修饰符。原因很简单,接口里面的方法都需要由外面接口实现去实现方法体,那么其修饰符必然是public。C#接口中的成员默认是public的,java中是可以加public的。
(2)接口成员不能有new、static、abstract、override、virtual修饰符。有一点要注意,当一个接口实现一个接口,这2个接口中有相同的方法时,可用new关键字隐藏父接口中的方法。
(3)接口中只包含成员的签名,接口没有构造函数,所有不能直接使用new对接口进行实例化。接口中只能包含方法、属性、事件和索引的组合。接口一旦被实现,实现类必须实现接口中的所有成员,除非实现类本身是抽象类。
(4)C#是单继承,接口是解决C#里面类可以同时继承多个基类的问题。
3.程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Bird
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
interface IFly
{
//接口中没有访问修饰符
void Fly();
}
interface ISpeak
{
void Speak();
}
class Mq : Bird, IFly
{ //在子类中实现接口中的方法
public void Fly()
{
Console.WriteLine("飞啊飞");
}
}
class Qe : Bird
{
}
class Yw : Bird, IFly, ISpeak
{
public void Fly()
{
Console.WriteLine("飞飞飞飞");
}
public void Speak()
{
Console.WriteLine("hello");
}
}
class Program
{
static void Main(string[] args)
{ //接口不能实例化
IFly fly = new Mq();
fly.Fly();
IFly f = Create("yw");
f.Fly();
Yw y = new Yw();
y.Fly();
y.Speak();
Console.ReadLine();
}
//简单的工厂模式
static IFly Create(string bird)
{
IFly fly = null;
switch(bird){
case "mq":
fly = new Mq(); break;
case "yw":
fly = new Yw(); break;
default: break;
}
return fly;
}
}
}