实现接口的类可以显式实现该接口的成员。当成员被显式实现时,它不能通过类实例访问,只能通过接口实例访问。
interface IDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
float lengthInches;
float widthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
float IDimensions.Length()
{
return lengthInches;
}
float IDimensions.Width()
{
return widthInches;
}
public static void Main()
{
Box myBox = new Box(30.0f, 20.0f);
IDimensions myDimensions = (IDimensions) myBox;
System.Console.WriteLine("Length: {0}", myDimensions.Length());
System.Console.WriteLine("Width: {0}", myDimensions.Width());
}
}
显式接口实现还允许程序员继承共享相同成员名称的两个接口,并为每个接口成员提供单独的实现。本示例显示了一个盒子的尺寸,包括公制和英制单位。Box类继承了两个接口IEnglishDimensions和IMetricDimensions,它们代表不同的测量系统。两个接口都具有相同的成员名称Length和Width。
请看示例:
interface IEnglishDimensions
{
float Length();
float Width();
}
interface IMetricDimensions
{
float Length();
float Width();
}
class Box : IEnglishDimensions, IMetricDimensions
{
float lengthInches;
float widthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
float IEnglishDimensions.Length()
{
return lengthInches;
}
float IEnglishDimensions.Width()
{
return widthInches;
}
float IMetricDimensions.Length()
{
return lengthInches * 2.54f;
}
float IMetricDimensions.Width()
{
return widthInches * 2.54f;
}
public static void Main()
{
Box myBox = new Box(30.0f, 20.0f);
IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
IMetricDimensions mDimensions = (IMetricDimensions) myBox;
System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
}
}
查看文章获取更多详情。