我想返回一個泛型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>
我這樣做不對嗎?或者有沒有其他的方法來完成這個,而不需要複製字典中的值?