gpt4 book ai didi

c# - > 的字典

转载 作者:行者123 更新时间:2023-11-30 14:58:37 24 4
gpt4 key购买 nike

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

**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 的约定。每个条目都有一个不同的类型键,每个项目列表都将遵循该类型的契约(Contract)。

最佳答案

你可以使用下面的静态类

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

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

关于c# - <Type, List<Type>> 的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18451565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com