我相信有许多同行对于interface和abstract的理解都各不一样,我想说说我个人的理解:
先说最基本概念:
一:interface(接口)
定义:接口只包含方法,属性,事件或索引器的签名。实现接口的类或者结构必须实现接口定义中指定的接口成员;
注意事项:
举例说明:
下面的例子演示了属性的声明,类中包含实现,实现类的任何实例都具有声明的属性:
interfaceIPoint
{
// Property signatures:
int x
{
get;
set;
}
int y
{
get;
set;
}
}
classPoint :IPoint
{
// Fields:
privateint _x;
privateint _y;
// Constructor:
publicPoint(int x,int y)
{
_x = x;
_y = y;
}
// Property implementation:
publicint x
{
get
{
return _x;
}
set
{
_x = value;
}
}
publicint y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
索引器的例子:
publicinterfaceISomeInterface
{
//声明索引器
intthis[int index]
{
get;
set;
}
}
// 实现接口
classIndexerClass :ISomeInterface
{
privateint[] arr =newint[100];
publicintthis[int index]
{
get
{
return arr[index];
}
set
{
arr[index] = value;
}
}
}
classMainClass
{
staticvoidMain()
{
IndexerClass test = new IndexerClass();
System.Random rand = new System.Random();
for (int i =0; i <10; i++)
{
test[i] = rand.Next();
}
for (int i =0; i <10; i++)
{
System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
}
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
方法和事件的例子就不再写了,大家肯定用的挺多的...
什么是显示接口实现呢?请看这个例子:
如果一个类实现的两个接口包含签名相同的成员,则在该类上实现此成员会导致这两个接口将此成员用作其实现。 如下示例中,所有对 Paint
的调用皆调用同一方法。
classTest
{
staticvoidMain()