C# 通过反射/类型名实例化泛型类

C# 通过反射/类型名实例化泛型类,c#,generics,reflection,C#,Generics,Reflection,例如,我有一个类,它看起来像: public class Repository<T> { public IEnumerable<T> FindAll() { // } } 公共类存储库 { 公共IEnumerable FindAll() { // } } 我希望能够通过反射创建存储库的实例 例如: var typeName = "Customer" var type = Assembly.GetCallingAssembly()

例如,我有一个类,它看起来像:

public class Repository<T>
{
    public IEnumerable<T> FindAll()
    {
        //
    }
}
公共类存储库
{
公共IEnumerable FindAll()
{
//
}
}
我希望能够通过反射创建存储库的实例

例如:

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

//obviously, this isn't valid...
var repository = new Repoistory<type>();
var typeName=“客户”
var type=Assembly.GetCallingAssembly().GetType(typeName);
//显然,这是无效的。。。
var repository=new repository();
这样做可能吗?

var repository=Activator.CreateInstance(typeof(repository).MakeGenericType(type));
var repository  = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(type));
下面是答案
。GetType(字符串)
采用完整的类型名,带有名称空间。