开发者

c# interface question

I have the following 开发者_JAVA技巧code:

// IMyInterface.cs

namespace InterfaceNamespace
{
    interface IMyInterface
    {
        void MethodToImplement();
    }
}

.

// InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{
    void IMyInterface.MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

This code compiles just fine(why?). However when I try to use it:

// Main.cs

    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
    }

I get:

InterfaceImplementer does not contain a definition for 'MethodToImplement'

i.e. MethodToImplement is not visible from outside. But if I do the following changes:

// InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

Then Main.cs also compiles fine. Why there is a difference between those two?


By implementing an interface explicitly, you're creating a private method that can only be called by casting to the interface.


The difference is to support the situation where an interface method clashes with another method. The idea of "Explicit Interface Implementations" was introduced.

Your first attempt is the explicit implementation, which requires working directly with an interface reference (not to a reference of something that implements the interface).

Your second attempt is the implicit implementation, which allows you to work with the implementing type as well.

To see explicit interface methods, you do the following:

MyType t = new MyType();
IMyInterface i = (IMyInterface)t.
i.CallExplicitMethod(); // Finds CallExplicitMethod

Should you then have the following:

IMyOtherInterface oi = (MyOtherInterface)t;
oi.CallExplicitMethod();

The type system can find the relevant methods on the correct type without clashing.


if you are implementing an interface to a class then the methods in interface must be there in class and all methods should be public also.

class InterfaceImplementer : IMyInterface
{

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

and you can call the method like this

IMyInterface _IMyInterface = new InterfaceImplementer();
IMyInterface.MethodToImplement();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜