c#在运行时创建未知的泛型类型
本文关键字:泛型类型 未知 创建 运行时 | 更新日期: 2023-09-27 18:21:10
所以我有一个泛型类,它可能需要在自己的方法中创建一个具有不同泛型类型的实例,其类型是通过反射获得的。
这一点很重要,因为这个存储库将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
//Let's loop through all the properties.
PropertyAndAttributes _paa;
foreach(PropertyInfo Property in type.GetProperties())
{
//Create a new instance each time.
_paa = new PropertyAndAttributes();
//Adds the property and generates an internal collection of attributes for it too
_paa.AddProperty(Property);
bool MapPropertyAndAttribute = true;
//This is a class we need to map to another table
if (Property.PropertyType.Namespace == "System.Collections.Generic")
{
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;
}
}
}
//Add this to the list.
if (MapPropertyAndAttribute) PAA.AddPaa(_paa);
}
return PAA;
}
如此给定GenericRepository<T>
,我想做一个GenericRepository<string type obtained via reflection from the Property>
,我该怎么做?我需要用有效的东西替换的行是:
//var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString());
谢谢。
我认为您正在寻找MakeGenericType
方法:
// Assuming that Property.PropertyType is something like List<T>
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() }))