c# 9.0 协变 return 类型和接口

c# 9.0 covariant return types and interfaces

我有两个代码示例:

一个编译

    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

    }

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

虽然 C# 9 不支持接口中的协变 return 类型,但有一个简单的解决方法:

    interface A {
        object Method1();
    }

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