我可以创建泛型类型的词典? [英] Can I Create a Dictionary of Generic Types?
问题描述
我想创建一个Dictionary对象,具有字符串键,拿着这是泛型类型的值。我想,这将是这个样子:
I'd like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:
Dictionary<string, List<T>> d = new Dictionary<string, List<T>>();
和使我添加以下内容:
d.Add("Numbers", new List<int>());
d.Add("Letters", new List<string>());
我知道我能做到这一点的字符串列表,例如,使用语法如下:
I know that I can do it for a list of strings, for example, using this syntax:
Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d.Add("Key", new List<string>());
但我想这样做对泛型列表如果可能的话...
but I'd like to do it for a generic list if possible...
2的问题,然后:
- 这可能吗?
- 什么是语法?
非常感谢,
乔恩
Many thanks,
Jon
推荐答案
编辑:现在,我重读了问题...
Now I've reread the question...
您不能做到这一点,但自定义集合将它处理到一定程度。你基本上有一个通用的添加
方法:
You can't do this, but a custom collection would handle it to some extent. You'd basically have a generic Add
method:
public void Add<T>(string key, List<T> list)
(集合本身的不会的是通用的 - 除非你想使密钥类型一般的)
(The collection itself wouldn't be generic - unless you wanted to make the key type generic.)
您不能的在一个强类型的方式提取物的从它值不过,因为编译器将不知道哪种类型你使用特定密钥。如果您在关键的类型本身,你最终用的略的更好的局面,而是一个仍然不被现有集合的支持。这是我原来的答复是在回应的情况。
You couldn't extract values from it in a strongly typed manner though, because the compiler won't know which type you've used for a particular key. If you make the key the type itself, you end with a slightly better situation, but one which still isn't supported by the existing collections. That's the situation my original answer was responding to.
编辑:原来的答复,当我还没有完全正确读取的问题,但也有可能说明反正...
Original answer, when I hadn't quite read the question correctly, but which may be informative anyway...
没有,你不能做一个类型参数依赖于另一个,我害怕。这只是一个可能要前preSS泛型类型系统,但.NET的约束条件不允许的事情之一。有总是会这样的问题,和.NET设计师选择保留仿制药的相对的简单。
No, you can't make one type argument depend on another, I'm afraid. It's just one of the things one might want to express in a generic type system but which .NET's constraints don't allow for. There are always going to be such problems, and the .NET designers chose to keep generics relatively simple.
不过,你可以写一个收集非常轻松地强制执行。我有<一个href=\"http://$c$cblog.jonskeet.uk/2008/10/08/mapping-from-a-type-to-an-instance-of-that-type.aspx\">an例如,在一个博客帖子只保留一个值,但它会很容易地扩展,要使用清单。
However, you can write a collection to enforce it fairly easily. I have an example in a blog post which only keeps a single value, but it would be easy to extend that to use a list.
这篇关于我可以创建泛型类型的词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!