我有一个泛型类,可能需要在自己的方法中使用反射创建另一种泛型的实例。这很重要,因为这个Repository将
如果提供该方法可以更容易地看到问题。
感谢您的选择。
T
映射到数据库表中[我正在编写一个ORMish],如果表示T
的类有一个表示另一个表的集合,我需要能够实例化它并将其传递给Repository [就像《盗梦空间》一样]。如果提供该方法可以更容易地看到问题。
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>
,我想创建一个通过反射从属性中获得的string类型的GenericRepository<string>
,我应该怎么做?我需要替换的代码行是:
//var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString());
感谢您的选择。
System.Collections.Generic
的属性是如何声明的?它的类型参数<T>
是否与拥有该属性的GenericRepository<T>
的类型参数相同? - Sergey KalinichenkoTeacher
类中声明的属性是List<Class> Classes {/*getter and/or setter*/}
吗?那么Activator.CreateInstance(Property.GetType())
就可以工作了吗? - Sergey Kalinichenko