c# - 遍历通用字典会抛出异常

标签 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 接口(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/

相关文章:

c# - 当值为空时,Razor html 标签不会获取 ID

c# - 即时窗口 - 转换为日期时间?抛出异常但 (datetime) 没有

c# - 按正确顺序获取数据集子行

C#:检查 XML 中的重复元素

c# - 如何避免在新创建的 XElement 中获取空命名空间?

c# - 记录复杂类型的描述

c# - 事件是否保证会举行?

.net - 如何从字符串中删除加速符?

c# - 2 个相同的绑定(bind)......一个有效,另一个无效

.net - 如何管理 .NET 中报告的更改?