我在 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/