微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/csharp/98043.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐