c#界面问题

时间:2011-05-18 11:23:00

标签: c# inheritance interface

我有以下代码:

// IMyInterface.cs

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

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

此代码编译得很好(为什么?)。但是,当我尝试使用它时:

// Main.cs

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

我明白了:

InterfaceImplementer does not contain a definition for 'MethodToImplement'

即。从外面看不到MethodToImplement。但是,如果我做了以下更改:

// InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{

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

然后Main.cs编译也很好。为什么这两者之间存在差异?

3 个答案:

答案 0 :(得分:6)

通过implementing an interface explicitly,您创建的私有方法只能通过强制转换为接口来调用。

答案 1 :(得分:1)

不同之处在于支持接口方法与其他方法发生冲突的情况。介绍了“显式接口实现”的概念。

您的第一次尝试是显式实现,需要直接使用接口引用(而不是实现接口的引用)。

您的第二次尝试是隐式实现,它允许您使用实现类型。

要查看显式接口方法,请执行以下操作:

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

如果您有以下内容:

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

类型系统可以在没有碰撞的情况下找到正确类型的相关方法。

答案 2 :(得分:0)

如果要实现类的接口,那么接口中的方法必须在类中,并且所有方法也应该是公共的。

class InterfaceImplementer : IMyInterface
{

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

你可以这样调用这个方法

IMyInterface _IMyInterface = new InterfaceImplementer();
IMyInterface.MethodToImplement();
相关问题