开发者

Should I implement interface members explicitly or implicitly?

This question and Eric Lippert's answer got me wondering: How do you decide w开发者_如何学JAVAhether to use an explicit or implicit implementation when implementing methods of an interface?


(personally) I only see a need for explicit implementations when there is a clash between methods with the same signature.

For example, when implementing IEnumerable<T>, you should implement 2 methods GetEnumerator() which have the same signature, except for the return type. So you'll have to implement IEnumerable.GetEnumerator() explicitly:

public abstract class MyClass<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {
        return ...;
    }

    IEnumerator IEnumerable.GetEnumerator() // explicit implementation required
    {
        return GetEnumerator();
    }
}

Another use for an explicit implementation is if you don't want the method to be called through an object instance, but only through an interface. I personally think this doesn't make much sense, but in some very rare cases, it can be useful.


Philippe's answer is a practical, one, however, there are architectural considerations as well.

Interfaces are used to make classes compatible so that they can be consumed by other objects. If only those consuming objects need the functionality of the interface, then it should be restricted so - by the principle of least privilege. If would be unnecessary to expose that interface method to all other users of the class.

Paul


Another case for explicit interfaces is where the object needs to implement an interface to accept calls from an internal object, but you don't want to expose those as part of your API.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜