Generic type from string value

I have a custom class that relies on the generic type T to be passed. I only know what type is in string form, because that is how it is sent. I searched around but can't seem to find what I need. I can parse the string value for the type, but I need to parse it into ... something that I can pass as a generic parameter.


I rewrote my problem as such:

// Classes structure namespace Mynamespace { public interface IRequest { } public interface IHandler<T> where T : IRequest { void Handle(T item); } public class MyRequest : IRequest { } public class MyHandler : IHandler<MyRequest> { void Handle(MyRequest item) { } } } // The info I get, and I know typeString is a IRequest string typeString = "My"; object requestItem = [insert xml parsing here]; // I then create a handler, to handle the request Type typeHandler = Type.GetType("Mynamespace." + typeString + "Handler"); var handler = Activator.CreateInstance(typeHandler); Type typeRequest = Type.GetType("Mynamespace." + typeString + "Request"); // what I want to do: handler.Handle(requestItem); 

I cannot do this because the handler and requestItem are just objects. Therefore, I need to parse the "handler" to "typeHandler" and the requestItem to "typeRequest"

Edit: I figured this out, I used InvokeMember to access it. :)

 typeHandler.InvokeMember("Handle", BindingFlags.InvokeMethod, null, handler, new[] { requestItem }); 
+4
source share
3 answers

I realized I used InvokeMember to access it. :)

 typeHandler.InvokeMember("Handle", BindingFlags.InvokeMethod, null, handler, new[] { requestItem }); 
0
source

You need Type.MakeGenericType :

 Type typeArgument = Type.GetType(string.Format("Mynamespace.{0}", typeString)); Type template = typeof(MyClass<>); Type genericType = template.MakeGenericType(typeArgument); object instance = Activator.CreateInstance(genericType); 

Note that you cannot attribute this to a specific MyClass<T> because you don't know T - but it will be an instance of the class you want at runtime.

+7
source
 Type closedType = typeof(MyClass<>).MakeGenericType(myGeneric); object obj = Activator.CreateInstance(closedType); 

Please note that if you do not have a universal interface or a base type, it is very difficult to talk to this type of object (unless you are cheating using dynamic ). For example, a non-generic interface may be useful:

 var obj = (ISomeInterface)Activator.CreateInstance(closedType); obj.SomeMethodOnTheNonGenericInterface(); 
+3
source

All Articles