c# – 是否不可能动态使用泛型?

前端之家收集整理的这篇文章主要介绍了c# – 是否不可能动态使用泛型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How do I use reflection to call a generic method?8个
我需要在运行时创建一个使用泛型的类的类,例如类< T>,而不必先前知道它们将具有的类型T,我想做这样的事情:
  1. public Dictionary<Type,object> GenerateLists(List<Type> types)
  2. {
  3. Dictionary<Type,object> lists = new Dictionary<Type,object>();
  4.  
  5. foreach (Type type in types)
  6. {
  7. lists.Add(type,new List<type>()); /* this new List<type>() doesn't work */
  8. }
  9.  
  10. return lists;
  11. }

…但我不能.我认为不可能在通用括号中的C#中写入一个类型变量.还有另一种做法吗?

解决方法

你不能这样做 – 泛型的点主要是编译时类型安全 – 但是你可以用反射来做:
  1. public Dictionary<Type,object>();
  2.  
  3. foreach (Type type in types)
  4. {
  5. Type genericList = typeof(List<>).MakeGenericType(type);
  6. lists.Add(type,Activator.CreateInstance(genericList));
  7. }
  8.  
  9. return lists;
  10. }

猜你在找的C#相关文章