C#:在实现方法中显式指定接口
为什么在实现接口时,如果我将方法设为公共,则不必显式指定接口,但如果将其设为私有,则必须...像这样(GetQueryString
是来自 IBar 的方法):
public class Foo : IBar
{
//This doesn't compile
string GetQueryString()
{
///...
}
//But this does:
string IBar.GetQueryString()
{
///...
}
}
那么为什么当方法设为私有时必须显式指定接口,而当方法设为公共时则不必显式指定接口?
Why is it that when implementing an interface, if I make the method public I do not have to explicitly specify the interface, but if I make it private I have to...like such (GetQueryString
is a method from IBar):
public class Foo : IBar
{
//This doesn't compile
string GetQueryString()
{
///...
}
//But this does:
string IBar.GetQueryString()
{
///...
}
}
So why do you have to specify the interface explicitly when the method is made private, but not when the method is public ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显式接口实现是公共和私有之间的一种折衷方案:如果您使用接口类型的引用来获取它,那么它就是公共的,但这是访问它的唯一方式(甚至在同一个班)。
如果您使用隐式接口实现,则需要将其指定为 public,因为它是一个公共方法,您要通过它位于接口中来重写它。 换句话说,有效的代码是:
就我个人而言,我很少使用显式接口实现,除非像
IEnumerable
这样的东西需要它,它根据是否是GetEnumerator
具有不同的签名泛型或非泛型接口:这里您必须使用显式接口实现以避免尝试基于返回类型进行重载。
Explicit interface implementation is a sort of half-way house between public and private: it's public if you're using an interface-typed reference to get at it, but that's the only way of accessing it (even in the same class).
If you're using implicit interface implementation you need to specify it as public because it is a public method you're overriding by virtue of it being in the interface. In other words, the valid code is:
Personally I rarely use explicit interface implementation unless it's required for things like
IEnumerable<T>
which has different signatures forGetEnumerator
based on whether it's the generic or non-generic interface:Here you have to use explicit interface implementation to avoid trying to overload based on return type.