接口是把所需成员组合起来,以封装一定功能的集合。它好比一个模板,在其中定义了对象必须实现的成员,通过类或结构来实现它。接口不能直接实例化,即ICount ic=new iCount()是错的。接口不能包含成员的任何代码,只定义成员本身。接口成员的具体代码由实现接口的类提供。接口使用interface关键字进行声明。声明格式如下:
[attributes] [modifiers] interface identifier [: base-list] {interface-body} {;}
接口成员的默认访问方式是public,在声明接口成员时不能出现abstract、public、protected、internal、private、virtual、override或static等关键字。接口成员可以是方法、属性、索引指示器或事件,不能是字段,而且接口的成员名不能相同。
using System.Collections.Generic;
using System.Text;
namespace Interface
{
interface ICount
{
void Count(); // 接口成员的默认访问方式是public
// int number; // 接口中不能定义字段成员
int para { get ; set ;}
}
class Double : ICount
{
public void Count()
{ // 实现ICount的Count()方法
Console.WriteLine( " The double para is {0} " , 2 * para);
}
int p;
public int para
{
get { return p; }
set { p = value; }
}
}
class Program
{
static void Main( string [] args)
{
Double d = new Double();
d.para = 10 ; // 给"属性"赋值
d.Count();
ICount ic = (ICount)d; // 转换为接口
ic.para = 5 ;
ic.Count();
Console.ReadLine();
}
}
}
1 一个类可以实现一个以上的接口; 2 类必须实现接口中的“所有”属性和方法; 3 属性和方法定义所采用的格式必须与接口定义所采用的格式完全相同。方法所采用的参数数目及参数类型必须与接口中的完全相同。方法的名称也必须相同。
接口之间的继承:接口的继承仅仅说明了接口之间的继承关系,派生的接口继承了父接口的成员说明,没有继承父接口的实现。private和internal类型的接口不允许继承。如果派生接口中准备重写父接口的方法,实现方式同类的继承成员的覆盖。
如果一个类实现了某个接口,即使父接口没有在类的基类表中列出,这个类也隐式地继承了接口的所有父接口。
如果两个接口A和B含有同名的成员Method,且都由同一个类C实现,则类C必须分别为A和B的Method成员提供单独的实现,即显式实现接口成员。可行方案(1)直接实现一个接口的成员,显式实现另一个接口的成员;(2)显式实现两个接口的成员
using System.Collections.Generic;
using System.Text;
namespace Interface
{
interface IEnglish
{
float Length();
float Width();
}
interface IMetric
{
float Length();
float Width();
}
class Class1 : IEnglish, IMetric
{
float lengthInches;
float widthInches;
public Class1( float length, float width)
{
lengthInches = length;
widthInches = width;
}
// 显式实现IEnglish的成员
float IEnglish.Length()
{
return lengthInches;
}
float IEnglish.Width()
{
return widthInches;
}
// 显式实现IMetric的成员
float IMetric.Length()
{
return lengthInches * 2.54f ;
}
float IMetric.Width()
{
return widthInches * 2.54f ;
}
static void Main( string [] args)
{
Class1 c1 = new Class1( 30.0f , 20.0f );
IEnglish e = (IEnglish)c1;
IMetric m = (IMetric )c1;
Console.WriteLine( " Length(in):{0} " ,e.Length());
Console.WriteLine( " Width(in):{0} " ,e.Width());
Console.WriteLine( " Length(cm):{0} " ,m.Length());
Console.WriteLine( " Width(cm):{0} " ,m.Width());
Console.ReadLine();
}
}
}
执行结果: