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());
相关推荐
nexttake几秒前
5.go-zero集成gorm 和 go-redis
开发语言·后端·golang
VBA633727 分钟前
VBA技术资料MF383:处理Excel中存储为文本的数据
开发语言
CiLerLinux33 分钟前
第三章 FreeRTOS 任务相关 API 函数
开发语言·单片机·物联网·c#
.NET修仙日记40 分钟前
C#/.NET 微服务架构:从入门到精通的完整学习路线
微服务·c#·.net·.net core·分布式架构·技术进阶
友友马2 小时前
『 QT 』QT控件属性全解析 (二)
开发语言·数据库·qt
逐步前行6 小时前
C标准库--C99--布尔型<stdbool.h>
c语言·开发语言
QX_hao6 小时前
【Go】--闭包
开发语言·golang
林月明9 小时前
【VBA】自动设置excel目标列的左邻列格式
开发语言·excel·vba·格式
喜欢吃燃面9 小时前
数据结构算法题:list
开发语言·c++·学习·算法·1024程序员节
。TAT。9 小时前
C++ - 多态
开发语言·c++·学习·1024程序员节