黑马程序员技术交流社区
标题: C#中的接口 [打印本页]
作者: yangaidongcumt 时间: 2013-6-13 19:47
标题: C#中的接口
本帖最后由 yangaidongcumt 于 2013-6-22 16:25 编辑
显示实现接口,这个是什么意思?求解释~~~
作者: ﹏Lifeヽ 时间: 2013-6-13 20:02
使用接口名作为方法名的前缀,这称为“显式接口实现”;传统的实现方式,称为“隐式接口实现”
作者: 江湖一浪人 时间: 2013-6-13 20:07
要实现借口.net中提供了两种形式:显式和隐式,你说的是显式实现
以下就来说说他们的选择:
隐式实现对象声明为接口和类都可以访问到其行为, 显式实现只有声明为接口可以访问。
隐式和显式接口实现的关键区别显然并不在于方法声明,而是在于从类外部的可访问性。
隐式实现不仅可以通过接口名称进行调用,还可以通过实现了接口的类进行调用。
显式声明只能通过接口名称调用实现接口的类。
谢谢!!!!!!
作者: 许庭洲 时间: 2013-6-13 20:16
本帖最后由 许庭洲 于 2013-6-13 20:18 编辑
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////声明一个 接口 IDimensions 和一个类 Box,该类显式实现接口成员 getLength 和 getWidth。通过接口实例 dimensions 访问这些成员。////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
interface IDimensions
{
float getLength();
float getWidth();
}
class Box : IDimensions
{
float lengthInches;
float widthInches;
Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
//Explicit interface member implementation:
float IDimensions.getLength()
{
return lengthInches;
}
//Explicit interface member implementation:
float IDimensions.getWidth()
{
return widthInches;
}
static void Main()
{
//Declare a class instance box1:
Box box1 = new Box(30.0f, 20.0f);
//Declare an interface instance dimensions:
IDimensions dimensions = (IDimensions)box1;
//The following commented lines would produce compilation
//errors because they try to access an explicitly implemented
//interface member from a class instance:
//System.Console.WriteLine("Length: {0}", box1.getlength());
//System.Console.WriteLine("Width: {0}", box1.getwidth());
//Print out the dimensions of the box by calling the methods
//from an instance of the interface:
System.Console.WriteLine("Length: {0}", dimensions.getLength());
System.Console.WriteLine("Width: {0}", dimensions.getWidth());
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Length: 30
Width: 20
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |