2009-03-09 2 views
2
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>; 

} 

答えて

7

これを試してみてください:

return _pool[myType].Values.Cast<EntityType>(); 

これは、列挙内のすべての要素をキャストする効果があります。

1

_poolは、そのためタイプDictionary<Type, Dictionary<EntityIdType, Object>>

のものとして定義されているタイプは、あなたがIEnumerble<EntityType>に直接キャストすることはできませんICollection<Object>を返すために、ディクショナリへの呼び出しが返されました。むしろ

、この質問の他の回答で示されているようにあなたは、キャストの拡張メソッドを使用する必要があります。

Cannot cast Dictionary ValueCollection to IEnumarable<T>. What am I missing?

関連する問題