欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

c#如何显式实现接口成员

时间:2021-05-03 10:03:22|栏目:.NET代码|点击:

本示例声明一个接口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());

上一篇:C#异步执行任务的方法

栏    目:.NET代码

下一篇:asp.net实现Gradview绑定数据库数据并导出Excel的方法

本文标题:c#如何显式实现接口成员

本文地址:http://www.codeinn.net/misctech/114023.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有