首页 文章

迭代通用字典会抛出异常

提问于
浏览
3

我有以下代码:

private Dictionary<int, Entity> m_allEntities;
private Dictionary<Entity, List<IComponent>> m_entityComponents;

public Dictionary<int, T> GetComponentType<T>() where T: IComponent
{
    Dictionary<int, T> components = new Dictionary<int, T>();

    foreach (KeyValuePair<int, Entity> pair in m_allEntities)
    {
        foreach (T t in m_entityComponents[m_allEntities[pair.Key]])
        {
            components.Add(pair.Key, t);
        }
    }

    return components;
}

m_allEntities =具有密钥的所有实体的字典:它们的ID和值:实体对象 . m_entityComponents =所有实体的字典及其组件列表,包含密钥:实体对象和值:它是组件列表 .

我有几个不同的类来实现IComponents接口 . GetComponentType()函数应该做的是遍历所有实体并创建实体ID和特定类型组件的字典 .

例如:如果我想获得具有Location组件的所有实体的列表,那么我将使用:

entityManager.GetComponentType<Location>();

我遇到的问题是第二个循环,因为它似乎没有通过我的字典过滤 . 相反,它尝试将字典中的所有组件强制转换为Location类型,当然,它会抛出异常 . 如何更改此代码以使其完成我想要的操作?

2 回答

  • 4

    你可以使用.OfType<T>方法:

    foreach (T t in m_entityComponents[m_allEntities[pair.Key]].OfType<T>())
    

    过滤与您的泛型类型匹配的元素 .

  • 2

    如果您的集合有不同的类型,则需要测试正确的类型 .

    public Dictionary<int, T> GetComponentType<T>() where T: IComponent
    {
        Dictionary<int, T> components = new Dictionary<int, T>();
    
        foreach (KeyValuePair<int, Entity> pair in m_allEntities)
        {
            foreach (IComponent c in m_entityComponents[m_allEntities[pair.Key]])
            {
                if (c is T)
                    components.Add(pair.Key, (T)c);
            }
        }
    
        return components;
    }
    

相关问题