因此,我有一个泛型类,它可能需要在其自己的方法内使用不同类型的泛型创建自身的实例,其类型是通过反射获得的。
这很重要,因为这个存储库映射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());
Thanks.
我想你正在寻找MakeGenericType method:
// 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)