Is the use of explicit interface implementation me

2020-06-17 03:45发布

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?

标签: c# interface
4条回答
Summer. ? 凉城
2楼-- · 2020-06-17 04:18

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.

查看更多
疯言疯语
3楼-- · 2020-06-17 04:19

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.
查看更多
SAY GOODBYE
4楼-- · 2020-06-17 04:27

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() { ... };
    }
}
查看更多
家丑人穷心不美
5楼-- · 2020-06-17 04:34

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.

查看更多
登录 后发表回答