Is the use of explicit interface implementation meant for hiding functionality?

浪子不回头ぞ 提交于 2019-12-09 11:23:54

问题


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?


回答1:


There are two main uses for it in my experience:

  • It allows you to overload methods by return value. For example, IEnumerable<T> and IEnumerable both declare GetEnumerator() 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> implements IList<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.



回答2:


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() { ... };
    }
}



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/6129857/is-the-use-of-explicit-interface-implementation-meant-for-hiding-functionality

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!