C#如何从派生类调用接口方法

sat*_*ite 0 c#

我有一个实现接口的类IPerson。我想从我的类中调用接口中实现的方法,但出现此错误:CS0103 当前上下文中不存在名称“SayMyName” 如何从派生类调用接口中实现的方法?

public interface IPerson
{
    string SayMyName()
    {
        return "MyName";
    }
}

public class Person : IPerson
{
    public void Method()
    {
        SayMyName();//ERROR CS0103 The name 'SayMyName' does not exist in the current context
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*erg 5

您需要显式转换才能访问由接口提供的默认实现。

((IPerson)this).SayMyName();
Run Code Online (Sandbox Code Playgroud)