所以我有一个通用类,它可能需要在它的一个方法内部自己创建一个不同类型的通用实例,该类型通过重新获得。c#在运行时创建一个未知的通用类型
这很重要,因为这个知识库将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我会怎么做呢? 我需要一些作品来替代该生产线是
// var x = Activator.CreateInstance("GenericRepository", Property.GetType().ToString());
是怎样的属性(类型的一个'系统.Collections.Generic')在你的C#代码中声明?它的类型参数''与拥有该属性的'GenericRepository '相同吗? –
dasblinkenlight
不,基本上它只是另一个类的泛型集合,作为一个类的属性。 即一个教师类有一个类的类列表。 版本库获取教师类,并且还必须处理类类,但是由于它确实获取了T,因此必须找出它使用反射必须处理的内容。 – Jordan
因此,将'Teacher'类中的属性声明为List类{/ * getter和/或setter * /}'?那么'Activator.CreateInstance(Property.GetType())'工作吗? –
dasblinkenlight