加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:17:02 所属栏目:百科 来源:网络整理
导读:参见英文答案 C# Interfaces. Implicit implementation versus Explicit implementation11个 是否有任何理由在实现类的方法名称之前包含接口引用?例如,假设您有一个ReportService:IReportService和一个GetReport(int reportId)方法.我正在审查一些代码,另
参见英文答案 > 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读