D. *_*ick 13 c# c#-8.0 default-interface-member
如果我有一个像这样的默认接口方法:
public interface IGreeter
{
void SayHello(string name) => System.Console.WriteLine($"Hello {name}!");
}
Run Code Online (Sandbox Code Playgroud)
我可以让我的具体实现调用该默认方法吗?
public class HappyGreeter : IGreeter
{
public void SayHello(string name)
{
// what can I put here to call the default method?
System.Console.WriteLine("I hope you're doing great!!");
}
}
Run Code Online (Sandbox Code Playgroud)
所以调用:
var greeter = new HappyGreeter() as IGreeter;
greeter.SayHello("Pippy");
Run Code Online (Sandbox Code Playgroud)
结果如下:
// Hello Pippy!
// I hope you're doing great!!
Run Code Online (Sandbox Code Playgroud)
事实上,从实现类中调用 C# 接口默认方法表明我可以调用我的类未实现的方法,但正如预期的那样,添加对((IGreeter)this).SayHello(name);内部的调用HappyGreeter.SaysHello会导致堆栈溢出。
据我所知,您无法在继承类中调用默认接口方法实现(尽管有建议)。但你可以从继承接口中调用它:
public class HappyGreeter : IGreeter
{
private interface IWorkAround : IGreeter
{
public void SayHello(string name)
{
(this as IGreeter).SayHello(name);
System.Console.WriteLine("I hope you're doing great!!");
}
}
private class WorkAround : IWorkAround {}
public void SayHello(string name)
{
((IWorkAround)new WorkAround()).SayHello(name);
}
}
Run Code Online (Sandbox Code Playgroud)
UPD
在我最初的回答中,我非常注重表明您可以在继承接口中调用基一,但正如@Alexei Levenkov在评论中建议的那样,在这种特殊情况下,更干净的方式将类似于以下内容:
public class HappyGreeter : IGreeter
{
private class WorkAround : IGreeter { }
private static readonly IGreeter _workAround = new WorkAround();
public void SayHello(string name)
{
_workAround.SayHello(name);
System.Console.WriteLine("I hope you're doing great!!");
}
}
Run Code Online (Sandbox Code Playgroud)