在c#中隐式和显式实现接口有什么不同?
什么时候用隐式,什么时候用显式?
这两者之间有什么利弊吗?
微软的官方指南(来自第一版框架设计指南)指出,不建议使用显式实现,因为它会给代码带来意想不到的行为。
我认为这个准则在前ioc时代是非常有效的,当你不把东西作为接口传递的时候。
有人能谈谈这方面的问题吗?
在c#中隐式和显式实现接口有什么不同?
什么时候用隐式,什么时候用显式?
这两者之间有什么利弊吗?
微软的官方指南(来自第一版框架设计指南)指出,不建议使用显式实现,因为它会给代码带来意想不到的行为。
我认为这个准则在前ioc时代是非常有效的,当你不把东西作为接口传递的时候。
有人能谈谈这方面的问题吗?
当前回答
我发现自己最近更经常地使用显式实现,原因如下:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync
其他回答
引用Jeffrey Richter从CLR通过c#编写的 (EIMI的意思是显式接口方法实现)
It is critically important for you to understand some ramifications that exist when using EIMIs. And because of these ramifications, you should try to avoid EIMIs as much as possible. Fortunately, generic interfaces help you avoid EIMIs quite a bit. But there may still be times when you will need to use them (such as implementing two interface methods with the same name and signature). Here are the big problems with EIMIs: There is no documentation explaining how a type specifically implements an EIMI method, and there is no Microsoft Visual Studio IntelliSense support. Value type instances are boxed when cast to an interface. An EIMI cannot be called by a derived type.
如果您使用接口引用,ANY虚链可以在任何派生类上显式地替换为EIMI,并且当这种类型的对象强制转换到接口时,您的虚链将被忽略,并调用显式实现。这根本不是多态性。
EIMIs还可以用于从基本框架接口的实现(如IEnumerable<T>)中隐藏非强类型接口成员,这样你的类就不会直接公开非强类型方法,但在语法上是正确的。
如果显式实现,则只能通过与接口类型相同的引用引用接口成员。实现类类型的引用不会公开这些接口成员。
如果实现的类不是公共的,除了用于创建类的方法(可以是工厂或IoC容器),并且除了接口方法(当然),那么我认为显式实现接口没有任何好处。
否则,显式实现接口将确保不使用对具体实现类的引用,从而允许您在以后更改该实现。“确保”,我想,是“优势”。一个分解良好的实现可以在没有显式实现的情况下完成这一点。
在我看来,缺点是您会发现自己在实现代码中对接口进行类型转换,而接口可以访问非公共成员。
就像许多事情一样,优势就是劣势(反之亦然)。显式实现接口将确保不会公开具体的类实现代码。
我大多数时候使用显式接口实现。以下是主要原因。
重构更安全
当改变一个接口时,最好是编译器能检查它。这对于隐式实现来说比较困难。
我想到了两种常见的情况:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below). Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
不幸的是,c#没有一个关键字来强制我们将一个方法标记为隐式实现,这样编译器就可以做额外的检查。由于需要使用“override”和“new”,虚拟方法不存在上述任何一个问题。
注意:对于固定的或很少变化的接口(通常来自供应商的API),这不是问题。但是,对于我自己的接口,我无法预测它们何时/如何改变。
这是自我记录
如果我在一个类中看到'public bool Execute()',它将需要额外的工作来确定它是接口的一部分。有人可能会评论它,或者把它放在一组其他接口实现中,所有这些都在一个区域或分组评论下,说“实现的ITask”。当然,这只在组头不在屏幕外的情况下才有效。
'bool ITask.Execute()'是清晰且无二义性的。
清晰分离的接口实现
我认为接口比公共方法更“公共”,因为它们被精心设计为只暴露了混凝土类型的一小部分表面积。他们将类型简化为一种能力、一种行为、一组特征等等。在实现中,我认为保持这种分离是有用的。
当我浏览一个类的代码时,当我遇到显式的接口实现时,我的大脑会切换到“代码契约”模式。通常,这些实现只是简单地转发到其他方法,但有时它们会做额外的状态/参数检查,转换传入参数以更好地匹配内部需求,甚至转换为版本控制目的(即多代接口都转移到公共实现)。
(我意识到公开也是代码契约,但是接口要强大得多,特别是在接口驱动的代码库中,直接使用具体类型通常是内部代码的标志。)
相关:Jon的原因2。
等等
加上其他答案中已经提到的优势:
当需要时,根据消除歧义或需要内部接口 不鼓励“为实现编程”(Jon的原因1)
问题
生活并不全是乐趣和幸福。在某些情况下,我坚持使用隐式:
值类型,因为这将需要装箱和较低的性能。这不是一个严格的规则,取决于接口和它的使用方式。IComparable吗?隐式。IFormattable吗?可能明确。 具有经常被直接调用的方法的普通系统接口(如IDisposable.Dispose)。
此外,当您确实拥有具体类型并希望调用显式接口方法时,执行强制转换可能会很麻烦。我有两种处理方法:
添加公共对象并将接口方法转发给它们以供实现。在内部工作时,通常发生在更简单的接口上。 (我的首选方法)添加一个公共IMyInterface I {get{返回这个;}}(应该内联)并调用foo.I.InterfaceMethod()。如果有多个接口需要此功能,则将名称扩展到I以外(根据我的经验,我很少有这种需求)。
隐式接口实现是指具有与接口相同签名的方法。
显式接口实现是显式声明方法属于哪个接口的地方。
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN:隐式和显式接口实现
隐式定义是将接口需要的方法/属性等直接作为公共方法添加到类中。
显式定义强制只在直接使用接口而不是底层实现时才公开成员。在大多数情况下,这是首选。
By working directly with the interface, you are not acknowledging, and coupling your code to the underlying implementation. In the event that you already have, say, a public property Name in your code and you want to implement an interface that also has a Name property, doing it explicitly will keep the two separate. Even if they were doing the same thing I'd still delegate the explicit call to the Name property. You never know, you may want to change how Name works for the normal class and how Name, the interface property works later on. If you implement an interface implicitly then your class now exposes new behaviours that might only be relevant to a client of the interface and it means you aren't keeping your classes succinct enough (my opinion).