Your sample code will not work because the generic method expects a type identifier, not an instance of the Type class. For this you need to use reflection:
public class Example { public void CallingTest() { MethodInfo method = typeof (Example).GetMethod("Test"); MethodInfo genericMethod = method.MakeGenericMethod(typeof (string)); genericMethod.Invoke(this, null); } public void Test<T>() { Console.WriteLine(typeof (T).Name); } }
Keep in mind that this is very fragile, I would prefer to find another template to call your method.
Another hacky solution (maybe someone can make it a little cleaner) would be to use some expression magic:
public class Example { public void CallingTest() { MethodInfo method = GetMethod<Example>(x => x.Test<object>()); MethodInfo genericMethod = method.MakeGenericMethod(typeof (string)); genericMethod.Invoke(this, null); } public static MethodInfo GetMethod<T>(Expression<Action<T>> expr) { return ((MethodCallExpression) expr.Body) .Method .GetGenericMethodDefinition(); } public void Test<T>() { Console.WriteLine(typeof (T).Name); } }
Note the passing of an identifier of type "object" as an argument of a generic type to lambda. Failed to figure out how to get around this so quickly. In any case, I think it is safe to compile. He somehow feels wrong: /
Erik van Brakel Sep 10 '09 at 22:56 2009-09-10 22:56
source share