C# 无法转换类型';System.Collections.Generic.Dictionary<;类,类>;。ValueCollection到System.Collections.Generic.ICollection<;T>;
我正在尝试将泛型ValueCollection作为ICollection返回。从MSDN文档中可以看出Dictionary.ValueCollection实现了ICollection接口。但由于某种原因,当需要将ValueCollection转换为ICollection时,我收到了一个错误。这是代码示例,下面是我收到的错误C# 无法转换类型';System.Collections.Generic.Dictionary<;类,类>;。ValueCollection到System.Collections.Generic.ICollection<;T>;,c#,xamarin-studio,C#,Xamarin Studio,我正在尝试将泛型ValueCollection作为ICollection返回。从MSDN文档中可以看出Dictionary.ValueCollection实现了ICollection接口。但由于某种原因,当需要将ValueCollection转换为ICollection时,我收到了一个错误。这是代码示例,下面是我收到的错误 public ICollection<T> GetAllComponents<T>() where T : Component {
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;
}
public ICollection GetAllComponents(),其中T:Component
{
Dictionary.ValueCollection retval=null;
如果(!this.componentitydatabase.ContainsKey(typeof(T)))
{
Logger.w(Logger.GetSimpleTagForCurrentMethod(this),“在数据库中找不到组件”+typeof(T.Name+);
返回新列表();
}
Dictionary entityRegistry=this.componentEntityDatabase[typeof(T)];
retval=entityRegistry.Values;
返回(ICollection)retval;
}
错误:
Cannot convert type 'Systems.Collections.Generic.Dictionary<Entity,Component>.ValueCollection' to System.Collections.Generic.ICollection<T>
无法将类型“Systems.Collections.Generic.Dictionary.ValueCollection”转换为System.Collections.Generic.ICollection
我做错了吗?或者有没有其他方法可以在不复制字典中的值的情况下完成此操作?在这种情况下,
ValueCollection
实现ICollection
,而不是ICollection
。即使T
必须是组件
,也不能保证所有值都是T
类型
这里有几个选择:
- 将返回类型更改为
ICollection
- 如果从
返回的字典中的所有值都是componentEntityDatabase
类型,请将T
更改为entityRegistry
dictionary
- 使用
仅返回of type
类型的值:T
retval = entityRegistry.Values.OfType<T>().ToList(); // turn into a List to get back to `ICollection<T>`
retval=entityRegistry.Values.OfType().ToList();//变成一个列表,返回“ICollection”
T
的对象。使用类型为的可能是最安全的方法