【发布时间】:2018-07-04 15:35:57
【问题描述】:
我有以下sn-p
using System.Collections.Generic;
public interface IInventoryItem {}
public class InventoryItem : IInventoryItem {}
public interface IInventory
{
IEnumerable<IInventoryItem> Items { get; }
}
public class Inventory : IInventory
{
public IEnumerable<InventoryItem> Items => items;
// IEnumerable<IInventoryItem> IInventory.Items => items;
private InventoryItem[] items = new InventoryItem[0];
}
我收到以下错误消息:
错误 CS0738:
Inventory未实现接口成员IInventory.Items.get和最佳实现候选Inventory.Items.get返回类型System.Collections.Generic.IEnumerable<InventoryItem>与接口成员返回类型System.Collections.Generic.IEnumerable<IInventoryItem>不匹配
添加IInventory.Items.get 的显式实现完全正确,但为什么有必要?
问题是:如果InventoryItem[] 是IEnumerable<IInventoryItem>,为什么IEnumerable<InventoryItem> 不是IEnumerable<IInventoryItem>?
编辑:
关于为什么这很有趣: 我的假设:
-
Items.get将始终返回一个有效的IEnumerable<T>IEnumerable<IInventoryItem>
【问题讨论】:
-
抛开泛型差异不谈,这个要求总是一直存在:如果一个接口说返回类型是
object,你就不能用一个方法来实现它返回string。覆盖时也是如此。 -
如果要使用具体类型,为什么需要接口?
-
接口将存在于另一个程序集中,这就是我需要它们的原因。
-
当有人告诉你你把界面放在任何地方,因为它很好,就会发生这种情况。它最终会被糟糕地使用。
标签: c# covariance