【问题标题】:c# 9.0 covariant return types and interfacesc# 9.0 协变返回类型和接口
【发布时间】: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


【解决方案1】:

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

    interface A {
        object Method1();
    }

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

【讨论】:

  • 当涉及泛型时,我似乎无法将此解决方案应用于界面中的任何类型的集合属性。你能说明当对象是 IList 时该怎么做吗?
  • @NWoodsman 它应该完全一样。你能说明哪些代码不工作吗?
  • 抱歉,我无意中试图获得与 IList<IFoo> 的通用协方差。
猜你喜欢
  • 2017-05-15
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多