2012-09-14 167 views
0

例如,我有一个类,看起来像:实例化通过反射泛型类/类型名称

public class Repository<T> 
{ 
    public IEnumerable<T> FindAll() 
    { 
     // 
    } 
} 

我想什么是能够做到的,就是通过建立一个反射库的一个实例。

例如:

var typeName = "Customer" 
var type = Assembly.GetCallingAssembly().GetType(typeName); 

//obviously, this isn't valid... 
var repository = new Repoistory<type>(); 

是沿着这些线路可能的东西吗?

+0

这里就是答案http://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection – opewix

+0

'.GetType(串);'采用完整的类型名称和命名空间。 http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx –

回答

1
var repository = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(type));