c# - 为什么我不能在显式实现接口(interface)的类中调用方法?

标签 c# interface explicit

这是故事。我创建了一个接口(interface),IVehicle。我在我的类 Vehicle.cs 中明确实现了该接口(interface)。

这是我的界面:

Interface IVehicle
{
        int getWheel();
}

这是我的类(class):

class Vehicle: IVehicle
{

     public int IVehicle.getWheel()
     {
         return wheel;
     }

     public void printWheel()
     {
         Console.WriteLine(getWheel());
     }
}

注意 getWheel() 是显式实现的。现在,当我尝试在我的 Vehicle 类中调用该方法时,我收到一条错误消息,指示 getWheel() 在当前上下文中不存在。有人可以帮助我了解我做错了什么吗?

最佳答案

显式实现接口(interface)时,首先必须将对象转换为接口(interface),然后才能调用方法。换句话说,只有当方法作为接口(interface)类型而不是具体类型在对象上调用时,该方法才可用。

class Vehicle: IVehicle {

     public int IVehicle.getWheel()
     {
         return wheel;
     }

     public void printWheel()
     {
         Console.WriteLine( ((IVehicle)this).getWheel() );
     }
}

查看此 reference在 MSDN 获取更多信息。这是相关的片段:

It is not possible to access an explicit interface member implementation through its fully qualified name in a method invocation, property access, or indexer access. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.

就其值(value)而言——这可能不是对显式接口(interface)实现的特别好的使用。通常,当您的类具有用于典型操作的完整接口(interface)但也实现了可以取代其中一些操作的接口(interface)时,您希望使用显式实现。典型示例是实现 IDisposableFile 类。它会有一个 Close() 方法,但需要实现 Dispose()。将其视为 File 时,您将使用 Open/Close。但是,当在 using 语句中打开时,它将把它视为 IDisposable 并调用 Dispose。在这种情况下,Dispose 只是调用 Close。您不一定希望将 Dispose 公开为 File 实现的一部分,因为可以从 Close 获得相同的行为。

关于c# - 为什么我不能在显式实现接口(interface)的类中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2520727/

相关文章:

c# - 捕获 ASP.NET Web Api 中所有未处理的异常

java - 在接口(interface)的所有实现上调用基函数

c# - 通过 ref : cannot convert from 'Foo' to 'ref IFoo' 传递实现

c++ - 为什么 boost::shared_array 的显式构造函数会导致错误?

c# - 通用显式转换失败 C#

c# - 动态添加的 ImageButton 命令事件直到第二次单击才触发

c# - 使用#IF指令检测单元测试

c# - 有没有办法将我的控制台应用程序转换为 C# 中的 Windows 窗体应用程序?

c# - 将对象转换为正确的类型

c++ - 我的 C++ 模板失败 : explicit specialization of non-template struct