c# - 在 C# 类中找不到默认接口(interface)

标签 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
    {

    }
}

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

'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?)

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

最佳答案

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

例如:

// This works
IPerson person = new Person();
person.GetName();

但是:

// Doesn't works
Person person = new Person();
person.GetName();

如果您想从类中调用默认接口(interface)方法,那么您需要将 this 转换为 IPerson 才能执行此操作:

private string SomeMethod()
{
  IPerson self = this;
  return self.GetName();
}

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

abstract class PersonBase
{
  public virtual string GetName()
  {
    return "Jonny";
  }
}

关于c# - 在 C# 类中找不到默认接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864296/

相关文章:

c# - 如何在未指定路径的代码隐藏中创建绑定(bind)?

c# - 在 Windows 8 Store 应用程序中按回车键移动到下一个控件

c# - 匹配参数的可空性和返回类型的泛型类型参数

c# - 删除字符串中分隔符之间的文本(使用正则表达式?)

.net - 不带await的异步方法

.net - Dotnet Core Nuget 设置代理

c# - .net 核心应用程序目标 Linux 上的 .net framework 4.5.2

visual-studio-2019 - Visual Studio 建议使用 C# 8.0 功能,但编译器产生错误

c# - 上课做什么? (带问号的类)在 C# 泛型类型约束中是什么意思?

c# - 如何在 C# 中用 8 位表示 4 位二进制数?