2013-08-21 273 views
0

我想返回一個泛型ValueCollection作爲ICollection。從他MSDN文檔說,Dictionary.ValueCollection實現了ICollection接口。不過,出於某種原因,我需要將ValueCollection強制轉換爲ICollection時收到錯誤消息。這是代碼示例,下面是我收到的錯誤。不能將類型'System.Collections.Generic.Dictionary <Class,Class> .ValueCollection轉換爲System.Collections.Generic.ICollection <T>

public ICollection<T> GetAllComponents<T>() where T : Component 
    { 
     Dictionary<Entity, Component>.ValueCollection retval = null; 

     if(!this.componentEntityDatabase.ContainsKey(typeof(T))) 
     { 
      Logger.w (Logger.GetSimpleTagForCurrentMethod (this), "Could not find Component " + typeof(T).Name + " in database"); 
      return new List<T>(); 
     } 

     Dictionary<Entity, Component> entityRegistry = this.componentEntityDatabase [typeof(T)]; 

     retval = entityRegistry.Values; 

     return (ICollection<T>)retval; 

    } 

錯誤:

Cannot convert type 'Systems.Collections.Generic.Dictionary<Entity,Component>.ValueCollection' to System.Collections.Generic.ICollection<T> 

我這樣做不對嗎?或者有沒有其他的方法來完成這個,而不需要複製字典中的值?

回答

0

在這種情況下,ValueCollection執行ICollection<Component>而不是ICollection<T>。即使T必須是Component,但您不能保證所有值都是T

這裏有幾個選擇:

  • 更改返回類型ICollection<Component>
  • 如果一切從 componentEntityDatabase返回的字典中的值都 T類型,改變 entityRegistryDictionary<Entity, T>

  • 使用OfType返回只有值是T類型:

    retval = entityRegistry.Values.OfType<T>().ToList(); // turn into a List to get back to `ICollection<T>` 
    

編輯

更加密切關注後,你將不得不限制爲僅對象T型的結果。使用OfType可能是最安全的方法。

相關問題