6

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.

4

2 回答 2

17

当一个类显式实现一个接口时,为什么需要将类实例显式转换为接口才能使用实现的方法?

就编译器而言,该成员实际上不存在于类中 - 它仅存在于接口上。不过,您不必显式地强制转换 - 您只需要有一个具有接口的编译时类型的引用。这可以随心所欲地完成,包括隐式转换。

在上面的代码块中,为什么有

IControl c = (IControl)obj;

IControl c = obj;

你不必。隐式转换应该绝对没问题。您必须显式转换才能在单个表达式中调用该方法,例如

obj.Paint(); // Invalid
((IControl) obj).Paint(); // Valid

但是,如果您通过对接口类型的单独局部变量的赋值进行隐式转换,那很好 - 仍然使用接口类型的目标表达式调用该方法。

于 2013-11-06T15:47:25.050 回答
2

仅当一种类型从多个接口继承并且某些方法在多个接口中具有相同的名称/签名时,才需要显式接口实现。

休息是偏好和惯例的问题。

mpleClass obj = new SampleClass();
//obj.Paint();  // Compiler error. 

obj.Paint()--> 这是错误,因为当显式接口实现完成时,底层接口实现需要MSDN中指定的显式转换

在方法调用、属性访问或索引器访问中,无法通过其完全限定名称访问显式接口成员实现。显式接口成员实现只能通过接口实例访问,并且在这种情况下仅通过其成员名称引用。

于 2013-11-06T15:47:09.230 回答