Information Technology Reference
In-Depth Information
Accessing Explicit Interface Member Implementations
An explicit interface member implementation can only be accessed through a reference to the
interface. This means that even other class members can't directly access them.
For example, the following code shows the declaration of class MyClass , which implements
interface IIfc1 with an explicit implementation. Notice that even Method1 , which is also a
member of MyClass , can't directly access the explicit implementation.
The first two lines of Method1 produce compile errors because the method is trying to
access the implementation directly.
￿
Only the last line in Method1 will compile, because it casts the reference to the current
object ( this ) to a reference to the interface type, and uses that reference to the interface
to call the explicit interface implementation.
￿
class MyClass : IIfc1
{
void IIfc1.PrintOut(string s) // Explicit interface implementation
{
Console.WriteLine("IIfc1");
}
public void Method1()
{
PrintOut("..."); // Compile error
this.PrintOut("..."); // Compile error
( (IIfc1)this) .PrintOut("..."); // OK, call method
}
} Cast to a reference to the interface
This restriction has an important ramification for inheritance. Since explicit interface
member implementations can't even be accessed by other fellow class members directly, they
clearly can't be directly accessed by classes derived from the class implementing them either.
They must always be accessed through a reference to the interface.
Search WWH ::




Custom Search