Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

c# - explicit interface implementation, why explicit casting

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

The member effectively doesn't exist on the class, as far as the compiler's concerned - it only exists on the interface. You don't have to explicitly cast though - you just have to have a reference which has a compile-time type of the interface. That can be done however you like, including implicit conversions.

In the above code block, why do you have

IControl c = (IControl)obj;

as opposed to

IControl c = obj;

You don't have to. The implicit conversion should be absolutely fine. You would have to cast explicitly in order to call the method in a single expression, e.g.

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

But if you go through an implicit conversion via assignment to a separate local variable of the interface type, that's fine - the method is still being called with a target expression which is of the interface type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...