public class CustomCollectionType<T> : IEnumerable<T>
{
/* Implementation here, not really important */
}
public class Entity : EntityBase
{
/* Implentation here, not important */
}
编译器在我尝试使用这个通用方法时发出了警告。
public void LoopThrough(IEnumerable<EntityBase> entityList)
{
foreach(EntityBase entity in entityList)
{
DoSomething(entity);
}
}
尝试按照以下方式使用它:
CustomCollectionType<Entity> entityList;
/* Add items to list */
LoopThrough(entityList);
错误提示说我无法将CustomCollectionType<Entity>
转换为IEnumerable<EntityBase>
。
然而,我可以这样做:
public void Foo(EntityBase entity)
{
entity.DoSomething();
}
Foo(new Entity());
And this :
public void Bar(IEnumerable<Entity> entityList)
{ ... }
CustomCollectionType<Entity> entityList;
Bar(entityList);
为什么我不能在层级结构中的最高类中创建我的方法?这些类型显然是兼容的... 我有什么遗漏吗?
编辑:我想在不以任何方式更改现有类的情况下解决此问题,因此在任何类中创建新方法或实现其他接口都是不可能的。