当一个类显式实现一个接口时,为什么需要将类实例显式转换为接口才能使用已实现的方法?
(此示例取自此处:MSDN:显式接口实现)
您有两个如下的接口。
现在,要使用接口,您需要以下代码。
在上面的代码块中,为什么要有?
与...相反
(此示例取自此处:MSDN:显式接口实现)
您有两个如下的接口。
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
而且你需要显式地实现它们。
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
现在,要使用接口,您需要以下代码。
// 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.
在上面的代码块中,为什么要有?
IControl c = (IControl)obj;
与...相反
IControl c = obj;
?
我的困惑是因为,例如,您可以执行以下操作。IDictionary<string, string> c = new Dictionary<string, string>();
不需要显式地将 new Dictionary
强制转换为 IDictionary
。
谢谢。
IControl c
,这不够吗? - sakura-bloomIControl c = (IControl)obj;
可能会让人感到困惑。为什么他们要对一个隐式转换进行冗余的显式转换?这可能是疏忽导致的错误,也可能是为了更好的可读性。 - P.Brian.Mackey