Instantiating a generic class through reflection /

2019-06-11 06:03发布

问题:

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?

回答1:

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