mercredi 8 septembre 2021

Cannot add classes created via reflection to a container

I'm working on some code that involves some nasty reflection hacking. Currently, I am creating a both a instance of a class as well as a List<T> container for that class where the class used is determined by a string. Everything as of right now is contained within the same assembly.

Type containerType = typeof(List<>);

Assembly currentAsm = Assembly.GetExecutingAssembly();
Type applicationModelType = currentAsm.GetType("NamespaceName." + targetApplicationModel);

Type applicationModelContainerType = containerType.MakeGenericType(applicationModelType);
dynamic container = Activator.CreateInstance(applicationModelContainerType);

In this case targetApplicationModel is a string containing the name of a class used for both the objects and generic part for the list. Now I want to create an instance of that type and add it to the container:

var x = Activator.CreateInstance(applicationModelType);
container.Add(y);
var y = container.Item[0];

However the call to Add fails with

Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Core.dll
An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll
The best overloaded method match for 'System.Collections.Generic.List<MyType>.Add(MyType)' has some invalid arguments

I can be pretty certain by inspecting while debuggung that x is indeed an instance of MyType so I have no idea why the call fails.





Aucun commentaire:

Enregistrer un commentaire