Access to the static method from GenericClass <T>, where T is specified by an instance of type

I have a general class with a static method, this method uses a parameter like:

GenericClass<T> { public static void Method() { //takes info from typeof(T) } } 

Now I need to access this static method, but not just using GenericClass<KnownType>.Method() . I need to do this with a type instance. So:

 public void OutsiderMethod(Type T) { GenericClass<T>.Method() //it clear this line won't compile, for T is a Type instance //but i want some way to have access to that static method. } 

Using reflections, I can probably get a way to call this method using a string name using some MethodInfo materials. This is partly good, solves the issue. But if possible, I would like not to use this name as a string.

Any???

+4
source share
2 answers

Using common methods of non-general classes is easier to access than non-general methods of common classes.

You can create a helper method that just calls the real method:

 void OutsiderMethodHelper<T>() { GenericClass<T>.Method(); } 

Then you can get the MethodInfo for this method without looking at it by name:

 public void OutsiderMethod(Type T) { Action action = OutsiderMethodHelper<object>; action.Method.GetGenericMethodDefinition().MakeGenericMethod(T).Invoke(null, null); } 
+5
source

Here is an example of using an expression:

 public static class GenericHelper { public static object Invoke(Expression<Action> invokeMethod, object target, Type genericType, params object[] parameters) { MethodInfo methodInfo = ParseMethodExpression(invokeMethod); if (!methodInfo.DeclaringType.IsGenericType) throw new ArgumentException("The method supports only generic types"); Type type = methodInfo.DeclaringType.GetGenericTypeDefinition().MakeGenericType(genericType); MethodInfo method = type.GetMethod(methodInfo.Name); return method.Invoke(target, parameters); } public static object Invoke(Expression<Action> invokeMethod, Type genericType, params object[] parameters) { return Invoke(invokeMethod, null, genericType, parameters: parameters); } private static MethodInfo ParseMethodExpression(LambdaExpression expression) { Validate.ArgumentNotNull(expression, "expression"); // Get the last element of the include path var unaryExpression = expression.Body as UnaryExpression; if (unaryExpression != null) { var memberExpression = unaryExpression.Operand as MethodCallExpression; if (memberExpression != null) return memberExpression.Method; } var expressionBody = expression.Body as MethodCallExpression; if (expressionBody != null) return expressionBody.Method; throw new NotSupportedException("Expession not supported"); } } 

The method call will look like this:

 GenericHelper.Invoke(() => GenericClass<object>.Method(), typeof(string)); 
0
source

All Articles