c# - 为什么返回 List<T> 的方法不能实现返回 IEnumerable<T> 的方法?

标签 c# .net interface

我有一个具体的类,实现了带有方法签名的接口(interface)

IEnumerable<T> Foo()

List<T> Foo()

编译器显示List<T> Foo无法实现IEnumerable<T> Foo 。为什么?

最佳答案

为什么编译器会拒绝这个?

因为规范不允许这样做:

For purposes of interface mapping, a class member A matches an interface member B when:

  • A and B are methods, and the name, type, and formal parameter lists of A and B are identical.

  • [...]

(引自 C# 5.0 规范 - 13.4.4 接口(interface)映射)

如果将此功能添加到规范中是否存在任何技术障碍?

据我所知:

  • 由于这两种类型都是引用类型,因此它们保留表示形式。因此,这些签名之间存在二进制兼容性。
  • 返回类型的协方差是类型安全的,因为返回 List<T> 的方法返回 IEnumerable<T>接口(interface)调用者所期望的

C# 和 .NET 中是否已有类似功能?

是的。 .NET 4 支持:

  • 委托(delegate)返回类型的协方差:Func<List<T>>Func<IEnumerable<T>>
  • 接口(interface)协方差:IEnumerable<List<T>>IEnumerable<IEnumerable<T>

这为该功能的可行性提供了进一步的证据。

那为什么不支持呢?

只有 C# 团队的成员才能明确回答这个问题。

但在没有进一步证据的情况下,我们可以假设:

每个功能都需要指定、实现测试和维护的成本。所以开发者只能实现一些功能。他们会选择事半功倍的功能。因此可能有更高优先级的功能,但不值得他们花时间。

有解决方法吗?

只需使用显式接口(interface)实现:

class FooClass<T> : IFoo
{
    public List<T> Foo()
    {
         //do something
    }

    IEnumerable<T> IFoo.Foo()
    {
        return Foo();
    }
}

关于c# - 为什么返回 List<T> 的方法不能实现返回 IEnumerable<T> 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24211806/

相关文章:

.net - OpenCV - 缺少 dll

linux - linux 将在 eth0 和 eth0.1 之间使用哪个接口(interface)?

c# - 我的游戏如何在开始屏幕上有一个宽图标?

c# - WPF - 将背景颜色绑定(bind)到三个 slider ?

c# - 序列化 DataContract 和 NULL 数据成员

java - PersonQueue 不是抽象的,不会重写 Queue 中的抽象方法 addLast()

wcf - svcutil、WSDL 和生成的接口(interface)不足以实现

c# - 在网格布局中创建动态按钮 - 创建幻方 UI

c# - 如何从另一个类或窗口访问 WPF 中的控件

c# - 关于 .NET 的 2 个基本但有趣的问题