4

我想为将类型映射到该类型的通用列表的字典实现一个包装类。例如:

**Key**               **Value**
typeof(InterfaceA), List<InterfaceA>
typeof(InterfaceB), List<InterfaceB>
typeof(MyClass), List<MyClass>
...

然后我想通过使用类型与包装类进行交互。

public void NewEntry<T>()
{
    MyDict.Add(typeof(T), new List<T>());
}

public List<T> GetEntry<T>()
{
    return MyDict[typeof(T)];
}

public void RemoveEntry<T>()
{
    MyDict.Remove(typeof(T));
}

有什么优雅的方法可以做到这一点吗?

编辑:澄清一下,这一点是这样的

GetEntry<MyInterface>()

列表中的项目保证遵循 MyInterface 的合同。每个条目都有一个不同的类型键,每个项目列表都遵循该类型的合同。

4

3 回答 3

2

如果您愿意静态存储所有内容,则可以使用类型系统:

static class MyDict {
    private static class Data<T> {
        public static readonly List<T> items = new List<T>();
    }
    public static List<T> Get<T>() { return Data<T>.items; }
    public static void Add<T>(T item) { Data<T>.items.Add(item); }
}

请注意,这使得无法删除密钥(您无法卸载类型),尽管您可以Clear()这样做。

于 2013-08-26T19:39:52.443 回答
2

您可以使用以下静态类

public static class GenericLists
{
    private static Dictionary<Type, object> MyDict = new Dictionary<Type, object>();
    public static void NewEntry<T>()
    {
        MyDict.Add(typeof(T), new List<T>());
    }

    public static List<T> GetEntry<T>()
    {
        return (List<T>)MyDict[typeof(T)];
    }

    public static void RemoveEntry<T>()
    {
        MyDict.Remove(typeof(T));
    }

}

或者你可以使用

public class GenericLists<T>
{
    private Dictionary<Type, List<T>> MyDict = new Dictionary<Type, List<T>>();

    public void NewEntry()
    {
        MyDict.Add(typeof(T), new List<T>());
    }

    public List<T> GetEntry()
    {
        return MyDict[typeof(T)];
    }

    public void RemoveEntry()
    {
        MyDict.Remove(typeof(T));
    }
}

如果你真的想初始化它,但我认为静态会更好。

于 2013-08-26T19:33:25.783 回答
1

您也可以将其作为基于实例的类来执行(见下文),但如果它适合您,我的偏好是在静态类中使用静态变量,如“使用类型系统”帖子中演示的 SLaks。

public class GenericTypeListDictionary
{
    private readonly Dictionary<Type, object> _dictionaryOfLists = new Dictionary<Type, object>();

    public List<T> NewEntry<T>()
    {
        var newList = new List<T>();
        _dictionaryOfLists.Add(typeof(T), newList);
        return newList;
    }

    public List<T> GetEntry<T>()
    {
        object value;

        if (_dictionaryOfLists.TryGetValue(typeof(T), out value))
        {
            return (List<T>)value;
        }

        return null;
    }

    public void RemoveEntry<T>()
    {
        _dictionaryOfLists.Remove(typeof(T));
    }
}
于 2013-08-26T19:56:58.230 回答