mardi 17 mai 2016

Create any type instance from its string via reflection

Imagine the following scenario:

A user passes a string to the application, which represents a .NET-Type, e.g. string or System.IntPtr. Assuming, that the application in question has access to the assemblies, in which the given Types are defined, it can create an instance of the given type based on the string.

I have managed to create such an application; the problem is only, that I am not (yet) able to create "complex" or "nested" types, e.g.:

  • Generics like System.Tuple<string, System.Action>
  • Arrays of T like int[], System.IntPtr[], etc...
  • Pointer of T like int*, char**, Namespace.MyStruct*, etc...
  • Any (possible) combination of the cases above

My question is: How can I create such nested type instances, when only given the string representation of the type (and of course all required assemblies)?

Do the .NET BCL contain some sort of string --> Type-parser? Or do I have to use some form of recursive regex-parser and Activator.CreateInstance?


How would you solve this issue? [I do not need code, more a kind of advice]





Aucun commentaire:

Enregistrer un commentaire