When using explicit implementation of an interface, the members are forced to something more restricted than private in the class itself. And when the access modifier is forced, you may not add one.
Likewise, in the interface itself, all members are public. If you try to add a modifier inside an interface you will get a similar error.
Why are explicit members (very) private? Consider:
interface I1 { void M(); }
interface I2 { void M(); }
class C : I1, I2
{
void I1.M() { ... }
void I2.M() { ... }
}
C c = new C();
c.M(); // Error, otherwise: which one?
(c as I1).M(); // Ok, no ambiguity.
If those methods were public, you would have a name-clash that cannot be resolved by the normal overload rules.
For the same reason you cannot even call M()
from inside a class C
member. You will have to cast this
to a specific interface first to avoid the same ambiguity.
class C : I1, I2
{
...
void X()
{
M(); // error, which one?
((I1)this).M(); // OK
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…