c#在运行时创建未知的generics类型

所以我有一个generics的类,它可能需要在它的方法中自己创建一个自己的实例,使用不同类型的generics,这种类型是通过relfection获得的。

这很重要,因为这个Repository将T映射到数据库表[这是我正在编写的ORMish],如果代表T的类有一个代表另一个表的集合,我需要能够实例化并将其传递给存储库[ala Inception ]。
我提供的方法是为了让它更容易看到问题。

private PropertiesAttributesAndRelatedClasses GetPropertyAndAttributesCollection() { // Returns a List of PropertyAndAttributes var type = typeof(T); //For type T return an array of PropertyInfo PropertiesAttributesAndRelatedClasses PAA = new PropertiesAttributesAndRelatedClasses(); //Get our container ready PropertyAndAttributes _paa; foreach (PropertyInfo Property in type.GetProperties()) //Let's loop through all the properties. { _paa = new PropertyAndAttributes(); //Create a new instance each time. _paa.AddProperty(Property); //Adds the property and generates an internal collection of attributes for it too bool MapPropertyAndAttribute = true; if (Property.PropertyType.Namespace == "System.Collections.Generic") //This is a class we need to map to another table { PAA.AddRelatedClass(Property); //var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString()); } else { foreach (var attr in _paa.Attrs) { if (attr is IgnoreProperty) //If we find this attribute it is an override and we ignore this property. { MapPropertyAndAttribute = false; break; } } } if (MapPropertyAndAttribute) PAA.AddPaa(_paa); //Add this to the list. } return PAA; } 

所以给定GenericRepository,我想创建GenericRepository我该怎么做? 我需要替换的东西是WORKS

 // var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString()); 

我想你正在寻找MakeGenericType方法:

 // Assuming that Property.PropertyType is something like List Type elementType = Property.PropertyType.GetGenericArguments()[0]; Type repositoryType = typeof(GenericRepository<>).MakeGenericType(elementType); var repository = Activator.CreateInstance(repositoryType); 
 Activator.CreateInstance(typeof(GenericRepository<>).MakeGenericType(new Type[] { Property.GetTYpe() }))