Is the use of explicit interface implementation meant for hiding functionality?
I use interfaces for decoupling my code. I am curious, is the usage of explicit interface implementation meant for hiding functionality?
Example:
public class MyClass : IInterface
{
void IInterface.NoneWillCall(int ragh) { }
}
What is the benefit and specific use case of making this available only explicitly开发者_高级运维 via the interface?
There are two main uses for it in my experience:
- It allows you to overload methods by return value. For example,
IEnumerable<T>
andIEnumerable
both declareGetEnumerator()
methods, but with different return types - so to implement both, you have to implement at least one of them explicitly. Of course in this question both methods are provided by interfaces, but sometimes you just want to give a "normal" method with a different type (usually a more specific one) to the one from the interface method. - It allows you to implement part of an interface in a "discouraging" way - for example,
ReadOnlyCollection<T>
implementsIList<T>
, but "discourages" the mutating calls using explicit interface implementation. This will discourage callers who know about an object by its concrete type from calling inappropriate methods. This smells somewhat of interfaces being too broad, or inappropriately implemented - why would you implement an interface if you couldn't fulfil all its contracts? - but in a pragmatic sense, it can be useful.
One example is ICloneable. By implementing it explicitly, you can have still have a strongly typed version:
public class MyClass : ICloneable {
object ICloneable.Clone() {
return this.Clone();
}
public MyClass Clone() {
return new MyClass() { ... };
}
}
It is not meant for hiding methods but to make it possible to implement two methods with the same signature/name from different interface in to different ways.
If both IA and IB have the operation F you can only implement a different method for each F by explicitly implementing the interfaces.
It can be used for hiding. For example, some classess that implement IDisposable
do so explicitly because they also have a Close()
method which does the same thing.
You can also use the explicit interface definitions for when you are implementing two interfaces on one class and there is a signature clash and the functionality differs depending on the interface. However, if that happens it is usually a sign that your class is doing too much and you should look at splitting the functionality out a bit.
精彩评论