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

} 

Antwort

7

Versuchen Sie folgendes:

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

Dies hat den Effekt, jedes Element in der Aufzählung zu werfen.

1

_pool als von Dictionary<Type, Dictionary<EntityIdType, Object>> Typ definiert ist

Aus diesem Grund, wird der Anruf in das Wörterbuch für einen Typ zurück kehrt ein ICollection<Object>, die Sie nicht direkt an IEnumerble<EntityType> werfen können.

Vielmehr haben Sie die Cast-Erweiterung Methode zu verwenden, wie in der anderen Antwort auf diese Frage angegeben:

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

Verwandte Themen