【问题标题】:C#: Explicitly specifying the interface in an implementation's methodC#:在实现的方法中显式指定接口
【发布时间】:2010-11-03 14:44:47
【问题描述】:

为什么在实现接口时,如果我将方法设为公开,我不必显式指定接口,但如果我将其设为私有,我必须...喜欢这样(GetQueryString 是来自 IBar 的方法):

public class Foo : IBar
{
    //This doesn't compile
    string GetQueryString() 
    {
        ///...
    }

    //But this does:
    string IBar.GetQueryString() 
    {
        ///...
    }
}

那么为什么在方法设为私有时必须显式指定接口,而在方法设为公开时却不需要呢?

【问题讨论】:

  • 当您说不起作用时,您的意思是 - 无法编译或无法按预期运行?

标签: c# interface access-modifiers


【解决方案1】:

显式接口实现是介于公共和私有之间的一种中间方式:如果您使用接口类型的引用来获取它,它就是公共的,但这是唯一的访问方式它(即使在同一个班级)。

如果您使用的是隐式接口实现,则需要将其指定为公共的,因为它一个公共方法,因为它位于接口中,所以您要覆盖它。也就是说,有效的代码是:

public class Foo : IBar
{
    // Implicit implementation
    public string GetQueryString() 
    {
        ///...
    }

    // Explicit implementation - no access modifier is allowed
    string IBar.GetQueryString() 
    {
        ///...
    }
}

我个人很少使用显式接口实现,除非它需要 IEnumerable<T> 之类的东西,根据它是通用接口还是非通用接口,GetEnumerator 具有不同的签名:

public class Foo : IEnumerable<string>
{
    public IEnumerator<string> GetEnumerator()
    {
        ...
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Call to the generic version
    }
}

这里你必须使用显式接口实现来避免尝试基于返回类型重载。

【讨论】:

  • 乔恩,我在帖子中对我的代码进行了修改,因为我之前在准确映射我的代码时犯了一个错误。
猜你喜欢
  • 2011-05-28
  • 2016-06-27
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 2019-04-07
  • 1970-01-01
  • 2010-10-22
相关资源
最近更新 更多