windows C#-显式实现接口成员

本示例声明一个接口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 = 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());
    }
}
/* Output:
    Length: 30
    Width: 20
*/

可靠编程

请注意,注释掉了 Main 方法中以下行,因为它们将产生编译错误。 显式实现的接口成员不能从类实例访问:

复制代码
//System.Console.WriteLine("Length: {0}", box1.GetLength());
//System.Console.WriteLine("Width: {0}", box1.GetWidth());

另请注意 Main 方法中的以下行成功输出了框的尺寸,因为这些方法是从接口实例调用的:

复制代码
System.Console.WriteLine("Length: {0}", dimensions.GetLength());
System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
相关推荐
阿珊和她的猫21 分钟前
autofit.js: 自动调整HTML元素大小的JavaScript库
开发语言·javascript·html
喜欢吃燃面41 分钟前
C++算法竞赛:位运算
开发语言·c++·学习·算法
草莓熊Lotso44 分钟前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
开发语言·c++·经验分享·笔记·其他
谱写秋天1 小时前
Qt 5.5 的安装与配置(使用 VSCode编辑)
开发语言·vscode·qt
唐青枫1 小时前
别滥用 Task.Run:C# 异步并发实操指南
c#·.net
项目申报小狂人1 小时前
算法应用上新!自适应更新策略差分进化算法求解球形多飞行器路径规划问题,附完整MATLAB代码
开发语言·算法·matlab
阿珊和她的猫5 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
fouryears_234177 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~8 小时前
C#---StopWatch类
开发语言·c#