C#接口定义了多个功能

0 c# interface

有人可以帮助我理解为什么这不起作用:

public interface IInterface
{
    string GetString(string start);
    void DoSomething();
}

public class InterfaceImpl : IInterface
{
    string IInterface.GetString(string start)
    {
        return start + " okay.";
    }
    void IInterface.DoSomething()
    {
        Console.WriteLine(this.GetString("Go")); // <-- Error: InterfaceImpl does not contain a definition for GetString
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么我不能调用在实现中最明确定义的函数.

谢谢你的帮助.

Ale*_*kov 5

需要在接口类型的变量上调用显式实现的方法,通常使用强制转换:

   Console.WriteLine(((IInterface)this).GetString("Go"));
Run Code Online (Sandbox Code Playgroud)

如何在没有显式转换的情况下在内部调用显式接口实现方法中介绍了调用显式定义方法的更多变体


cru*_*ays 5

您不需要使用该方法显式指定接口.由于InterfaceImpl已经实现了IInterface,您只需要执行以下操作:

public class InterfaceImpl : IInterface
{
    public string GetString(string start)
    {
        return start + " okay.";
    }
    public void DoSomething()
    {
        Console.WriteLine(GetString("Go"));
    }
}
Run Code Online (Sandbox Code Playgroud)

根据评论更新.