我有以下代码:
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 接口(interface)的不同类。 GetComponentType() 函数应该做的是遍历所有实体并创建实体 ID 和特定类型组件的字典。
例如:如果我想获取所有具有 Location 组件的实体的列表,那么我将使用:
entityManager.GetComponentType<Location>();
我遇到的问题是第二个循环,因为它似乎没有通过我的词典进行过滤。相反,它尝试将字典中的所有组件转换为 Location 类型,这当然会引发异常。我怎样才能改变这段代码,让它做我想做的事?
最佳答案
如果您的集合有不同的类型,您需要测试正确的类型。
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;
}
关于c# - 遍历通用字典会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184001/