【问题标题】:any reason why an interface reference would be included before a method name on an implementing class? [duplicate]为什么在实现类的方法名称之前会包含接口引用? [复制]
【发布时间】:2017-05-15 00:44:19
【问题描述】:

是否有任何理由在实现类的方法名称之前包含接口引用?例如,假设您有一个 ReportService : IReportService 和一个 GetReport(int reportId) 方法。我正在查看一些代码,另一位开发人员在 ReportService 中实现了这样的方法:

Report IReportService.GetReport(int reportId)
{
  //implementation
}

我以前从未见过这样的服务实现。它有什么用吗?

【问题讨论】:

  • 可以肯定的是,如果实现类具有具有相同签名的方法,您可以区分。
  • 显式接口实现不允许您使用可见性修饰符。我很确定您只是在这里的问题中输入错误,所以继续编辑它。如果您认为我错了,如果您认为 public 确实存在,请随时恢复,但您无法编译。

标签: c# .net


【解决方案1】:

这称为“显式接口实现”。例如,其原因可能是命名冲突。

考虑接口IEnumerableIEnumerable<T>。声明一个非泛型方法

IEnumerator GetEnumerator();

另一个是通用的:

IEnumerator<T> GetEnumerator();

在 C# 中,不允许有两个名称相同但返回类型不同的方法。所以如果你实现了这两个接口,你需要显式声明一个方法:

public class MyEnumerable<T> : IEnumerable, IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    { 
        ... // return an enumerator 
    }

    // Note: no access modifiers allowed for explicit declaration
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // call the generic method
    }
}

不能对实例变量调用显式实现的接口方法:

MyEnumerable<int> test = new MyEnumerable<int>();
var enumerator = test.GetEnumerator(); // will always call the generic method.

如果你想调用非泛型方法,你需要将test 转换为IEnumerable

((IEnumerable)test).GetEnumerator(); // calls the non-generic method

这似乎也是为什么在显式实现上不允许访问修饰符(如publicprivate)的原因:无论如何它在类型上不可见。

【讨论】:

  • 您也可以从接口显式实现以实现非公开的东西(这可能是另一个原因)。
  • @M.kazemAkhgary 确实如此。值得补充的是,如果公共类实现了内部接口,并且内部接口声明了具有内部返回类型的方法,则公共类不能将其实现为公共方法,它必须 求助于显式接口实现。
猜你喜欢
  • 2017-12-18
  • 2013-01-20
  • 2021-01-19
  • 2019-08-19
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2013-08-16
相关资源
最近更新 更多