var _pool = new Dictionary<Type, Dictionary<EntityIdType, Object>>();
public IEnumerable<EntityType> GetItems<EntityType>()
{
Type myType = typeof(EntityType);
if (!_pool.ContainsKey(myType))
return new EntityType[0];
//does not work, always returns null
// return _pool[myType].Values; as IEnumerable<EntityType>;
//hack: cannot cast Values to IEnumarable directly
List<EntityType> foundItems = new List<EntityType>();
foreach (EntityType entity in _pool[myType].Values)
{
foundItems.Add(entity);
}
return foundItems as IEnumerable<EntityType>;
}
答案 0 :(得分:7)
试试这个:
return _pool[myType].Values.Cast<EntityType>();
这具有在枚举中转换每个元素的效果。
答案 1 :(得分:1)
_pool被定义为类型Dictionary<Type, Dictionary<EntityIdType, Object>>
因此,对类型返回的字典调用将返回ICollection<Object>
,您无法直接将其转换为IEnumerble<EntityType>
。
相反,您必须使用Cast扩展方法,如此问题的其他答案中所示:
Cannot cast Dictionary ValueCollection to IEnumarable<T>. What am I missing?