参见英文答案 >
How do I use reflection to call a generic method?8个
我需要在运行时创建一个使用泛型的类的类,例如类< T>,而不必先前知道它们将具有的类型T,我想做这样的事情:
我需要在运行时创建一个使用泛型的类的类,例如类< T>,而不必先前知道它们将具有的类型T,我想做这样的事情:
- public Dictionary<Type,object> GenerateLists(List<Type> types)
- {
- Dictionary<Type,object> lists = new Dictionary<Type,object>();
- foreach (Type type in types)
- {
- lists.Add(type,new List<type>()); /* this new List<type>() doesn't work */
- }
- return lists;
- }
…但我不能.我认为不可能在通用括号中的C#中写入一个类型变量.还有另一种做法吗?
解决方法
你不能这样做 – 泛型的点主要是编译时类型安全 – 但是你可以用反射来做:
- public Dictionary<Type,object>();
- foreach (Type type in types)
- {
- Type genericList = typeof(List<>).MakeGenericType(type);
- lists.Add(type,Activator.CreateInstance(genericList));
- }
- return lists;
- }