接口这个概念之前就已经接触,但由于目前为止使用较少,对它并不是很了解,而后经过查阅相关资料终于有了较为系统的理解。接口是一种用来定义程序的协议,有方法、属性、事件和索引器构成,但是只能起到定义作用,不能给这些成员设置具体的值。
接口具有如下特点:
1、 接口不能直接实例化
2、 接口可以定义方法、属性和索引
3、 接口不包含方法的实现
4、 继承接口的任何非抽象类型都要实现接口的所有成员
5、 类或结构可以继承自多个接口
6、 接口自身可以从多个接口继承
由于类不能支持多重继承,但是现实需要中却难免出现多重继承的情况,这种情况下就需要接口实现多重继承的功能。所以多重继承式接口的重要应用之一。
namespace 接口
{
interface IPeople
{
string Name
{
get;
set;
}
string Rank
{
get;
set;
}
}
interface IManager : IPeople
{
void Manage();
}
interface IWorker : IPeople
{
void Product();
}
class Program : IPeople, IManager ,IWorker
{
string name = "";
string rank = "";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Rank
{
get
{
return rank;
}
set
{
rank = value;
}
}
public void Manage()
{
Console.WriteLine(Name + "" + rank );
}
public void Product()
{
Console.WriteLine(Name + "" + Rank );
}
static void Main(string[] args)
{
Program program = new Program();
IManager imanager = program;
imanager.Name = "jingli";
imanager.Rank = "经理";
imanager.Manage();
IWorker iworker = program;
iworker.Name = "yuangong";
iworker.Rank = "员工";
iworker.Product();
}
}
}
实例显示了多重接口的应用。关于接口,值得一提的还有在它的使用中,还可能出现类需要实现两个包含相同签名成员的接口的情况,同时如果接口的两个成员实现不同功能,则可能出现几口不能实现或程序编译错误。这是需要使用显示接口。
namespace 显式接口
{
interface Icalculate1
{
int Add();
}
interface Icalculate2
{
int Add();
}
class Calculate: Icalculate1, Icalculate2
{
int Icalculate1.Add ()
{
int x = 6;
int y = 8;
return x + y;
}
int Icalculate2.Add()
{
int x = 3;
int y = 9;
int z = 6;
return x + y+ z;
}
}
class Program
{
static void Main(string[] args)
{
Calculate calculate = new Calculate();
Icalculate1 icalculate1 = calculate;
Console.WriteLine(icalculate1.Add());
Icalculate2 icalculate2 = calculate;
Console.WriteLine(icalculate2.Add());
}
}
}
计算结果为:
需要注意的是现实接口的成员不是类的成员,所以不能用类对象直接访问,只能通过对象和接口访问。