C# 无法转换类型';System.Collections.Generic.Dictionary<;类,类>;。ValueCollection到System.Collections.Generic.ICollection<;T>;

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 {

我正在尝试将泛型ValueCollection作为ICollection返回。从MSDN文档中可以看出Dictionary.ValueCollection实现了ICollection接口。但由于某种原因,当需要将ValueCollection转换为ICollection时,我收到了一个错误。这是代码示例,下面是我收到的错误

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
的对象。使用类型为的
可能是最安全的方法