我可以创建泛型字典吗? [英] Can I Create a Dictionary of Generic Types?

查看:24
本文介绍了我可以创建泛型字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含字符串键的 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>>();  

并使我能够添加以下内容:

And enable me to add the following:

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 个问题:

  1. 有可能吗?
  2. 语法是什么?

推荐答案

现在我重读了这个问题...

Now I've reread the question...

您不能这样做,但自定义集合会在一定程度上处理它.你基本上有一个通用的 Add 方法:

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...

不,恐怕你不能让一种类型的参数依赖于另一种类型的参数.这只是人们可能想要在泛型类型系统中表达但 .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.

但是,您可以编写一个集合来轻松执行它.我有 博客文章中的一个示例,它只保留一个值,但很容易将其扩展为使用列表.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆