在 c# 类中找不到默认接口

Fri*_*ren 4 c# .net-core c#-8.0 default-interface-member

我在 VS 16.5.1 上的控制台应用程序 .net core 3.1 中有这样的代码和平:

namespace DefaultInterfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {   
            var person = new Person();
            person.GetName();//error here
        }
    }

    public interface IPerson
    {
        string GetName()
        {
            return "Jonny";
        }
    }

    public class Person: IPerson
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我想我可以从这个人本身访问默认实现 oif GetName ,因为它是一个公共方法,但它会产生这个错误:

'Person' does not contain a definition for 'GetName' and no accessible extension method 'GetName' accepting a first argument of type 'Person' could be found (are you missing a using directive or an assembly reference?)
Run Code Online (Sandbox Code Playgroud)

如何从外部代码或 Person 类本身访问接口的默认实现?谢谢!

Sea*_*ean 6

您只能通过接口引用调用来访问默认实现方法(将它们视为显式实现的方法)。

例如:

// This works
IPerson person = new Person();
person.GetName();
Run Code Online (Sandbox Code Playgroud)

但:

// Doesn't works
Person person = new Person();
person.GetName();
Run Code Online (Sandbox Code Playgroud)

如果要从类中调用默认接口方法,则需要强制转换this为 anIPerson才能这样做:

private string SomeMethod()
{
  IPerson self = this;
  return self.GetName();
}
Run Code Online (Sandbox Code Playgroud)

如果您使用接口,则无法解决这种情况。如果你真的想要这种行为,那么你需要使用一个抽象类,其中GetName是一个虚方法。

abstract class PersonBase
{
  public virtual string GetName()
  {
    return "Jonny";
  }
}
Run Code Online (Sandbox Code Playgroud)