【问题标题】:How to call method which is explicitly implemented如何调用显式实现的方法
【发布时间】:2012-09-14 13:44:36
【问题描述】:

我在下面有一段代码。

interface IFirst
{
   void Show();
}

public class Test : IFirst
{
   void IFirst.Show()
   {
       Console.WriteLine("First");
   }
}

在实现类中,我无法为 Show() 提供公共访问说明符。 如何从主程序调用这个 Show()?

【问题讨论】:

  • ((IFirst)new Test()).Show();

标签: c# oop


【解决方案1】:

您必须将变量转换为接口类型,因为显式接口方法只能使用接口访问,而不能使用实现它们的类访问。使用显式接口实现是一种代码封装形式,可以让您隐藏类的实现细节(也允许实现许多方法名称冲突的接口)。

Test test = new Test();
var casted = test as IFirst;
casted.Show();

你也可以使用隐式转换发送变量到方法:

public void ShowMeATrick(IFirst first) {
    first.Show();
}

Test test = new Test();
ShowMeATrick(test);

【讨论】:

    【解决方案2】:

    显式接口方法只能通过接口访问,而不能通过实现它们的类。

    在您的代码中,您可以将类的实例强制转换为接口,然后引用明确定义的方法/属性。

    显式接口上的 MSDN 链接: http://msdn.microsoft.com/en-us/library/ms173157%28v=vs.100%29.aspx

    另一个问类似问题的问题: Compilation Error: "The modifier 'public' is not valid for this item" while explicitly implementing the interface

    【讨论】:

      【解决方案3】:

      试试,

      IFirst obj = new Test();
      obj.Show();
      

      【讨论】:

        猜你喜欢
        • 2010-10-19
        • 2011-08-23
        • 2011-03-21
        • 1970-01-01
        • 2011-04-08
        • 2012-07-10
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        相关资源
        最近更新 更多