【发布时间】:2021-03-21 15:36:18
【问题描述】:
我有两个代码示例:
一个编译
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 中如何工作以及为什么它不适用于接口?
【问题讨论】:
-
Covariant returns:“下面的规范草案的其余部分提出了对接口方法的协变返回的进一步扩展稍后考虑。”
-
@Damien_The_Unbeliever 没有在此处发现此评论。谢谢!
-
一种方法是将 A 更改为抽象类。另一种方法是添加一个从 A 派生的抽象类,该类具有虚拟 Method1,然后从该抽象类派生 B。两种选择都很丑。等 C# 也支持接口方法可能会更好。
标签: c# .net covariance c#-9.0