简体   繁体   中英

Having trouble passing type to a generic class with reflection

I have a class that has the following...

public class Client<T> : IClient where T : IClientFactory, new()
{
    public Client(int UserID){}
}

and another class that implements IClientFactory

public class Client : IClientFactory

If the dll is referenced then I can easily do this to instantiate it.

var data = new namespace.Client<namespace.OtherDLL.Client>(1);

But obviously if I try to do it with a loaded assembly this will fail as it doesn't know the type. I keep reading around to use Reflection to do it. But I try to implement those ideas and have failed. Here is an article about it. Can I pass a type object to a generic method?

Assembly myDllAssembly = Assembly.LoadFile(project.Path + project.Assembly);

Type type = myDllAssembly.GetType("Migration.Application.Client");

var data = new namespace.Client<type>(1);

Any help on this would be great, since I'm trying to just use a configuration file to allow me to easily drop DLL when they are ready to the client and just modify the config file to make things work.

You need to call the method using reflection:

var type = typeof(Client<>).MakeGenericType(type);
var data = (IClient)Activator.CreateInstance(type, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM