c# – 在实现类的方法名称之前包含接口引用的任何原因?

参见英文答案 > C# Interfaces. Implicit implementation versus Explicit implementation11个
是否有任何理由在实现类的方法名称之前包含接口引用?例如,假设您有一个ReportService:IReportService和一个GetReport(int reportId)方法.我正在审查一些代码,另一个开发人员在ReportService中实现了这样的方法:
Report IReportService.GetReport(int reportId)
{
  //implementation
}

我以前从未见过像这样的服务实现.它有用吗?

解决方法

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

考虑接口IEnumerable和IEnumerable< 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.

如果要调用非泛型方法,则需要将测试转换为IEnumerable:

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

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

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...