dimanche 9 août 2020

C# dynamically load generic class with dynamic type parameters per strings and strongly typed result

I am attempting to take a JSON file that contains data about a generic class (assembly, class name, type parameter names), and dynamically load and instantiate the specified class. I can do this if I use interfaces for the type parameter. However, implementation specifics won't allow me to go this route, so I need to use the specific type parameter classes.

I have the following code so far:

var ci = Invoke.GetClassRef(@"D:\ROCT\Debug\x64 Core\Common Complex Functions.dll", "Namespace.Class");
Type[] typeArgs = { typeof(DoubleABCAry), typeof(FloatABCAry), typeof(Search3Range), typeof(object) };
var _model = ci.GetType().MakeGenericType(typeArgs);
var model = Activator.CreateInstance(_model) as ComplexBaseModel<IModelInput, IModelIOBase, ISearchDimension, object>;
model.Validate();

Line 1: loads the assembly and class. No problem there.

Line 2: lists the types that I need to specify name-wise via a string[].

Line 4: DoubleABCAry implements IModelInput; FloatABCAry implements IModelIOBase, etc.

Line 4 is casting the object to its base definition (shown), which is not what I want. I want RGB255ToCIELAB : ComplexBaseModel<DoubleABCAry, FloatABCAry, Search3Range, object>.

Line 5 shows that the class is correctly understood. However, the class clearly is implementing interfaces, not the specific types I need.

Is there a way to achieve these two objectives:

  1. Use string names to specify each type parameter.
  2. Ultimately have model strongly typed as explained?

I know it's achievable with dynamically compiled code, but that is my last resort.

I am using C# 9 preview.





Aucun commentaire:

Enregistrer un commentaire