时间:2019-03-09 标签:c#9.0协变返回类型和接口

Ale*_*nko 20 .net c# covariance c#-9.0

我有两个代码示例:

一编译

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

    class D : C {
        public override string Method2() => throw new NotImplementedException();
    }
Run Code Online (Sandbox Code Playgroud)

另一种则没有

    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

    }
Run Code Online (Sandbox Code Playgroud)

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

Yai*_*adt 14

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

    interface A {
        object Method1();
    }

    class B : A {
        public string Method1() => throw new NotImplementedException();
        object A.Method1() => Method1();
    }
Run Code Online (Sandbox Code Playgroud)