C#9.0协变量返回类型和接口 [英] c# 9.0 covariant return types and interfaces

查看:63
本文介绍了C#9.0协变量返回类型和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个代码示例:

一个编译

    class C {
        public virtual object Method2() => throw new NotImplementedException();
    }

    class D : C {
        public override string Method2() => throw new NotImplementedException();
    }

另一人没有

    interface A {
        object Method1();
    }

    class B : A {
        public string Method1() => throw new NotImplementedException();
        // Error    CS0738  'B' does not implement interface member 'A.Method1()'. 'B.Method1()' cannot implement 'A.Method1()' because it does not have the matching return type of 'object'.  ConsoleApp2 C:\Projects\Experiments\ConsoleApp2\Program.cs  14  Active

    }

协变返回类型如何在C#9.0中工作,为什么它不适用于接口?

How covariant return types work in C# 9.0 and why it does not work with interfaces?

推荐答案

尽管从C#9开始不支持接口中的协变返回类型,但是有一个简单的解决方法:

Whilst covariant return types in interfaces are not supported as of C# 9, there is a simple workaround:

    interface A {
        object Method1();
    }

    class B : A {
        public string Method1() => throw new NotImplementedException();
        object A.Method1() => Method1();
    }

这篇关于C#9.0协变量返回类型和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆