通用列表或不同类型的字典 [英] Dictionary of generic lists or varying types
问题描述
我想要一个字典,将字符串映射到不同类型的通用列表。即采用以下格式:
I want to have a Dictionary that maps strings to generic lists of varying types. i.e. in the following form:
Key Value
string List<T>
string List<U>
string List<V>
string List<U>
...
当前我正在使用 Dictionary< string,IList>
,然后从每个字典 KeyValuePair< string,IList>中提取强类型列表。对
条目,如下所示:
Currently I'm using a Dictionary<string, IList>
and then extracted the strongly typed list from each dictionary KeyValuePair<string, IList> pair
entry as follows:
Type layerType = pair.Value.GetType().GetGenericArguments()[0];
List<layerType> objectsClicked = pair.Value as List<layerType>;
是否有更好的方法?
如前所述,以上内容并未编译,对不起-这是您在仍在进行某些工作时提出问题时所得到的。
更多解释。我正在制作一个基本的空间数据查看器。最终视图由一组 Layer< T>
s组成。每层都提供一个代表以渲染其类型(赋予偏移和比例)的委托,以及一种检查其对象在当前窗口中的方式。对于命中测试,我想要一个被击中对象的每一层的列表。该列表将是 Point
层的 List< Point>
,依此类推...所有的 Layer< T>
s都将是强类型列表的集合。
As has been noted, the above doesn't compile, apologies - that's what you get when you ask a question while you're still working on somethings.
Some more explanation. I'm making a basic spatial data viewer. The final view consists of a group of Layer<T>
s. Each layer provides a delegate to render its type (given an offset and scale) and a way to check which of its objects are in the current window. For hit testing, I would like a List for each Layer of which objects have been hit. That list would be a List<Point>
for a Point
layer, etc... The grouping of the hits from all the Layer<T>
s would then be a collection of strongly typed lists.
推荐答案
假设您使用的是C#4, Dictionary< string,dynamic>
怎么样
How about Dictionary<string, dynamic>
assuming you're on C# 4
Dictionary<string, dynamic> Dict = new Dictionary<string, dynamic>();
Dict.Add("int", new List<int>());
Dict.Add("string", new List<string>());
Dict["int"].Add(12);
Dict["string"].Add("str");
foreach (KeyValuePair<string, dynamic> pair in Dict) {
Type T = pair.Value.GetType();
Console.WriteLine(T.GetGenericArguments()[0].ToString());
}
打印出
System.Int32
System.Int32
System.String
System.String
这是您要找的东西吗?
这篇关于通用列表或不同类型的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!