迭代通用字典会抛出异常

时间:2012-02-07 21:11:37

标签: c# .net

我有以下代码:

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 个答案:

答案 0 :(得分:4)

如果您的收藏品有不同的类型,则需要测试正确的类型。

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;
}

答案 1 :(得分:2)

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

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

过滤与您的通用类型匹配的元素。