通过反射/类型名实例化一个泛型类 [英] Instantiating a generic class through reflection / typename

查看:186
本文介绍了通过反射/类型名实例化一个泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个类,如下所示:

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

我希望能够做的是通过反射来创建Repository的一个实例。



例如:

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

//显然,这是无效的...
var repository = new Repoistory< type>();

是否有这些可能?

解决方案

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


For example, I have a class, that looks like:

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

What I'd like to be able to do, is create an instance of a Repository via reflection.

For example:

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

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

Is something along these lines possible?

解决方案

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

这篇关于通过反射/类型名实例化一个泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆