Monday, 5 September 2011

Calling generic method, determining the type at runtime

//using Linq:
string paramTypeName = "System.Int32";
string someValue = "33";

Type paramType = Type.GetType(paramTypeName);

MethodInfo mymethod = typeof(MyLibrary.MyClass)
    .GetMethods(BindingFlags.Public | BindingFlags.Static)
    .First(m => m.Name == "MyGenericMethod" && m.GetParameters().Count() == 2);
 
object methodResult = mymethod.MakeGenericMethod(paramType).Invoke(nullnew object[] { 123, someValue });


inspired  by:
http://www.aaron-powell.com/reflection-and-generics
http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method

No comments:

Post a Comment