mercredi 29 août 2018

Creating instance of generic class using Assembly.GetType

I have a factory which creates instances of classes, given a fully qualified type name i.e. Instruments.ClassName

Namespace Instruments
    Public Class ClassName
        Implements IInstrument

This has always worked using this method

public Type LoadFromAssemblies(string className, IEnumerable<Assembly> assemblies)
{
    return assemblies.Select(Assembly a => a.GetType(className)).Single(t => t != null);
}

However, I've changed some classes to inherit from a base, instead of implement an interface, that that base has a generic parameter. The class is now generic

Namespace Instruments
    Public Class ClassName(Of T As ClassNameSettings)
        Inherits ClassNameBase(Of T)

The class name is Instruments.ClassName`1 with the `1 denoting 1 generic parameter. The method above no longer works as the type name doesn't match. If I know before calling LoadFromAssemblies that the class is generic, I could append `1 but I don't know at that point. I could also iterate assemblies multiple times, once for each number of possible generic parameters (up to one for now) but this function is called hundreds of times and it would seem wasteful.

So is there a good method for instantiating a generic class from a list of assemblies, given the non-generic type name?





Aucun commentaire:

Enregistrer un commentaire