开发者

public type modifiers for interface

When a class implements an interface, the type modifiers for the interface members should be public. Why开发者_高级运维 is there such a restriction?


An interface defines how other objects will communicate with objects of the type that implements that interface; Since other objects can only interact with the public properties and methods of other types, the interface must define those properties and methods as public.


There are two ways of implementing an interface method; the first is implicit implementation - which assumes the public API is exposing the interface methods, and is what you are no-doubt seeing.

However, you can also use explicit implementation:

void IDisposable.Dispose() {
    // clean up
}

is a trivial example; this is private, yet satisfies the interface. An explicit implementation always takes precedence over a like-named method on the public API.

In fact, explicit implementation is often necessary, for example to implement IEnumerable<T> - since there are two conflicting GetEnumerator() methods; the following is common:

// public API will be used for implicit IEnumerable<T>.GetEnumerator()
public IEnumerator<T> GetEnumerator() { ... do work ... }
// explicit implementation of IEnumerable.GetEnumerator()
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }

So: if you don't want public members; use explicit implementation.


Lets say an Interface can have Private members. When a class inherits the interface, the class will never be able to access the private member. The class will never be able to implement the private member and the program will never get compiled.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜