我有两个代码示例:
一个编译
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:ProjectsExperimentsConsoleApp2Program.cs 14 Active
}
协变返回类型在C#9.0中是如何工作的,为什么它不能与接口一起工作?
虽然从C#9开始不支持接口中的协变返回类型,但有一个简单的解决方法:
interface A {
object Method1();
}
class B : A {
public string Method1() => throw new NotImplementedException();
object A.Method1() => Method1();
}