我有一种情况,我有某种Item
和Collection
类的非泛型和泛型实现,其中集合必须包含 Items 并且泛型集合必须包含特定类型的泛型项。
public class Item { }
public class Item<T>: Item { }
public class MyList : IEnumerable<Item> {
public IEnumerator<Item> GetEnumerator() { }
}
public class MyList<T> : MyList, IEnumerable<Item<T>> {
public new IEnumerator<Item<T>> GetEnumerator() { }
}
问题是 Linq 扩展方法不适用于列表的通用版本:
// works
var test1 = new MyList().Any();
// intellisense understands this, but it won't compile
var test2 = new MyList<int>().Any();
这是使用 .NET 4.5。我认为这与两个冲突接口的存在有关,IEnumerable<Item>
并且IEnumerable<Item<T>>
. 我期望的是派生的优先。
为什么不能编译,什么是实现这样的正确方法,以便我可以IEnumerable<T>
在集合类的非泛型和泛型版本中公开接口?如果我只是从非通用版本中删除接口,一切都会正常工作IEnumerable<Item>
,但是当然我不能在不通过其他一些非标准方法公开它的情况下枚举它。
Error: MyList<T>' does not contain a definition for 'Any' and no extension method 'Any' accepting a first argument of type 'Item<T>' could be found (are you missing a using directive or an assembly reference?)