根据https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
可以使用以下语法显式调用接口(interface)基实现。
base(IInterfaceType).Method();
但这似乎还没有实现。
是否有解决方法(例如反射)来实现这一目标?
Example code to illustrate the problem
interface IA
{
void M()
{
Console.WriteLine("IA.M");
}
}
interface IB : IA
{
void IA.M()
{
Console.WriteLine("IB.M");
}
}
interface IC : IA
{
void IA.M()
{
Console.WriteLine("IC.M");
}
}
class D : IA, IB, IC
{
public void M()
{
// base(IB).M(); Is not yet supported apparently
((IB)this).M(); // Throws stack overflow
}
}
class Program
{
static void Main(string[] args)
{
D d = new D();
d.M();
}
}
最佳答案
问题中的链接指向复制的提案版本 from the proposal document in Github
该功能是cut in April 2019
Conclusion
Cut base() syntax for C# 8. We intend to bring this back in the next major release.
设计 session 文档解释说,如果没有运行时支持(不会及时可用),该实现最多只能用于 C#,但不适用于 VB.NET。
If B.M is not present at run time, A.M() will be called. For base() and interfaces, this is not supported by the runtime, so the call will throw an exception instead. We'd like to add support for this in the runtime, but it is too expensive to make this release.
We have some workarounds, but they do not have the behavior we want, and are not the preferred codegen. Our implementation for C# is somewhat workable, although not exactly what we would like, but the VB implementation would be much more difficult. Moreover, the implementation for VB would require the interface implementation methods to be public API surface.
至于无限递归,这
public void M()
{
((IB)this).M(); // Throws stack overflow
}
这本质上是
public void M()
{
M(); // Throws stack overflow
}
默认接口(interface)成员的调用方式与通过接口(interface)显式实现的接口(interface)方法相同。此外,您要求调用
this
上的方法,而不是 base
.
关于C# 8 基本接口(interface)的默认方法调用解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59398027/