C# 8 基本接口(interface)的默认方法调用解决方法

标签 c# reflection .net-core c#-8.0

根据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/

相关文章:

c# - 具有复杂类型的数据协定序列化

c# - 在 ASP.NET vNext 中使用 Ninject 时出现编译器错误 CS0246(未找到类型或命名空间)

c# - 数组和通用列表上 "GetElementType"的混淆结果

cookies - 如何在.net core中读取cookie过期时间?

c# - NETSDK1201 : For projects targeting . NET 8.0 及更高版本,默认情况下指定 RuntimeIdentifier 将不再生成自包含应用程序

c# - 缺少 using 指令或程序集引用 (ClientContext)

c# - 如何检查属性 setter 是否公开

java - 为什么不能通过反射访问公共(public)构造函数

c# - 如何使用Net Core获取DbContext中的用户信息

javascript - 如何在 ASP.NET Core MVC 中将 js 字符串发布到 C#