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

时间:2012-01-23 00:00:59

标签: c# reflection casting

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

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

    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());

2 个答案:

答案 0 :(得分:33)

我认为您正在寻找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);

答案 1 :(得分:4)

Activator.CreateInstance(typeof(GenericRepository<>).MakeGenericType(new Type[] { Property.GetTYpe() }))