c#9.0协变返回类型和接口
我有两个代码示例: 编辑c#9.0协变返回类型和接口,c#,.net,covariance,c#-9.0,C#,.net,Covariance,C# 9.0,我有两个代码示例: 编辑 class C { public virtual object Method2() => throw new NotImplementedException(); } class D : C { public override string Method2() => throw new NotImplementedException(); } 另一个没有 interface A {
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中如何工作以及为什么它不与接口一起工作?虽然从C#9开始不支持接口中的协变返回类型,但有一个简单的解决方法:
接口A{
对象方法1();
}
B类:A{
公共字符串方法1()=>抛出新的NotImplementedException();
对象A.Method1()=>Method1();
}
:“以下规范草案的其余部分建议进一步扩展接口方法的协变返回,以供以后考虑。”@Damien\u不信者没有注意到这句话。谢谢一种方法是将抽象类更改为抽象类。还有一种方法是添加一个抽象类,该抽象类派生自具有虚方法1的A,然后从该抽象类派生出B。这两种选择都是丑陋的。也许最好等到C#也支持接口方法。是的,这就是我现在解决问题的方式。