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

} 

cevap

7

bu deneyin:

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

Bu numaralandırma her eleman döküm etkisine sahiptir.

1

_pool nedenle

tip Dictionary<Type, Dictionary<EntityIdType, Object>> olmanın olarak tanımlanmaktadır, sözlüğe çağrısı bir türü için döndürülen Eğer IEnumerble<EntityType> doğrudan döküm olamaz bir ICollection<Object> döndürür. Bu soru için diğer yanıtında belirtildiği gibi

yerine, Cast uzantısı yöntemi kullanmak zorunda:

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

İlgili konular