如何从通用字典中获取值列表

bas*_*ner 0 c# generics dictionary

我已经使用这个ObjectPool类作为我的身份地图的基础.但是,我需要恢复一个类型的所有对象的列表.马修有:

    public IEnumerable<T> GetItems<T>()
    {
        Type myType = typeof(T);

        if (!m_pool.ContainsKey(myType))
            return new T[0];

        return m_pool[myType].Values as IEnumerable<T>;
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我像这样对客户端进行更改时:

        pool.AddItem<Animal>(dog.ID, dog);
        pool.AddItem<Vegetable>(carrot.Identifier, carrot);
        pool.AddItem<Vegetable>(greenbean.Identifier, greenbean);
        pool.AddItem<Mineral>(carbon.UniqueID, carbon);

        Console.WriteLine("Dog is in the pool -- this statement is " + pool.ContainsKey<Animal>(dog.ID));

        IEnumerable<Vegetable> veggies = pool.GetItems<Vegetable>();
        foreach(Vegetable veg in veggies)
            Console.WriteLine(string.Format("{0} - {1}", veg.Color, veg.IsTasty));
Run Code Online (Sandbox Code Playgroud)

蔬菜是空的.看来m_pool [myType] .Values不支持强制转换为IEnumerable.

我尝试过一些东西,例如:

        IDictionary<int, T> dic = (IDictionary<int, T>) m_pool[myType];
        ICollection<T> values = (ICollection<T>)dic.Values;
Run Code Online (Sandbox Code Playgroud)

但是,我总是最终会出现一个投射错误.

我错过了什么?

Jon*_*eet 9

好吧,这种GetItems方法永远不会起作用,看起来除非是Dictionary<int, object>.Values实现的.遗憾的是,这种方法从根本上被打破了 - 哦,对于一些单元测试.IEnumerable<T>Tobject

我建议您检查许可证,如果可以修复GetItems,请执行以下操作:

public IEnumerable<T> GetItems<T>()
{
    Type myType = typeof(T);

    IDictionary<int, object> dictionary;

    if (!m_pool.TryGetValue(myType, out dictionary))
    {
        return new T[0];
    }

    return dictionary.Values.Cast<T>();
}
Run Code Online (Sandbox Code Playgroud)

如果你使用的是.NET 3.5(你也需要using System.Linq获得Cast扩展方法).如果你需要.NET 2.0的东西,请告诉我.