问题描述
在 C# 中隐式和显式实现接口有什么区别?
What are the differences in implementing interfaces implicitly and explicitly in C#?
什么时候应该使用隐式,什么时候应该使用显式?
When should you use implicit and when should you use explicit?
其中一个有什么优点和/或缺点吗?
Are there any pros and/or cons to one or the other?
Microsoft 的官方指南(来自第一版 框架设计指南) 声明不推荐使用显式实现,因为它会给代码带来意想不到的行为.
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
我认为这个指南在 IoC 之前的时期非常有效,当你不把东西作为接口传递时.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
谁能也谈谈这方面的问题?
Could anyone touch on that aspect as well?
推荐答案
Implicit 是指通过类中的成员定义接口.显式 是在您的类中在接口上定义方法时.我知道这听起来令人困惑,但我的意思是:IList.CopyTo
将隐式实现为:
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo
would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
并明确表示为:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
不同之处在于隐式实现允许您通过您创建的类访问接口,方法是将接口转换为该类和接口本身.显式实现允许您仅通过将其转换为接口本身来访问该接口.
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
我使用显式主要是为了保持实现干净,或者当我需要两个实现时.无论如何,我很少使用它.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
我确信有更多理由使用/不使用其他人会发布的明确内容.
I am sure there are more reasons to use/not use explicit that others will post.
请参阅下一篇文章在这个线程中,每个背后都有很好的推理.
See the next post in this thread for excellent reasoning behind each.
这篇关于C# 接口.隐式实现与显式实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!