When a class explicitly implements an interface why do you need to explicitly cast the class instance to interface in order to use implemented method?
(This example is taken from here: MSDN: Explicit Interface Implementation)
You have two interfaces as follows.
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
And you implement them explicitly.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
Now, to use the interfaces you have the following code.
// Call the Paint methods from Main.
SampleClass obj = new SampleClass();
//obj.Paint(); // Compiler error.
IControl c = (IControl)obj;
c.Paint(); // Calls IControl.Paint on SampleClass.
ISurface s = (ISurface)obj;
s.Paint(); // Calls ISurface.Paint on SampleClass.
In the above code block, why do you have
IControl c = (IControl)obj;
as opposed to
IControl c = obj;
?
The reason for my confusion is because, for example, you can do the following
IDictionary<string, string> c = new Dictionary<string, string>();
without explicitly casting new Dictionary
to IDictionary
.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…