我有一个具体的类,实现了带有方法签名的接口(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/