2011-03-07 20 views
22

duplicados posibles:
How to use reflection to call generic Method?
Select Right Generic Method with ReflectionReflexión: ¿Cómo obtener un método genérico?

Hola

Digamos que tengo dos siguientes dos métodos en una clase:

public void MyMethod(object val) {} 
public void MyMethod<T>(T val) {} 

con la reflexión, que podría conseguir el primer método como este:

Type[] typeArray = new Type[1]; 
typeArray.SetValue(typeof(object), 1); 
var myMethod = myInstance.GetType().GetMethod("MyMethod", typeArray); 

Pero, ¿cómo puedo obtener el segundo, método genérico?

+0

Posible duplicado de: http://stackoverflow.com/questions/ 3631547/select-right-generic-method-with-reflection –

+1

@AakashM: Este * no es * un duplicado de esa pregunta en particular. – LukeH

+0

@LukeH cierto que eres. Aunque creo que es un duplicado de algo. – AakashM

Respuesta

37
var myMethod = myInstance.GetType() 
         .GetMethods() 
         .Where(m => m.Name == "MyMethod") 
         .Select(m => new { 
               Method = m, 
               Params = m.GetParameters(), 
               Args = m.GetGenericArguments() 
              }) 
         .Where(x => x.Params.Length == 1 
            && x.Args.Length == 1 
            && x.Params[0].ParameterType == x.Args[0]) 
         .Select(x => x.Method) 
         .First(); 
+1

thx - no esperaba ser tan complicado :-) – sl3dg3

+0

wow, eso es increíblemente molesto – Eric

7

lo haría así:

var methods = from m in typeof(MyClass).GetMethods() 
       where m.Name == "MyMethod" 
       && m.IsGenericMethodDefinition 

       let typeParams = m.GetGenericArguments() 
       let normalParams = m.GetParameters() 

       where typeParams.Length == 1 && normalParams.Length == 1 
       && typeParams.Single() == normalParams.Single().ParameterType 
       && !typeParams.Single().GetGenericParameterConstraints().Any() 

       select m; 

var myMethod = methods.Single(); 

Estamos buscando un método llamado "MiMetodo" que es un método genérico con un solo tipo de parámetros que no tienen limitaciones, y uno ' parámetro 'normal' del mismo tipo que el parámetro tipo.

Obviamente, si usted no está buscando ser muy preciso, sólo puede hacer lo mínimo para eliminar la ambigüedad, como por ejemplo:

var myMethod = typeof(MyClass) 
       .GetMethods() 
       .Single(m => m.Name == "MyMethod" && m.IsGenericMethodDefinition); 
+0

thx - la segunda consulta es una buena solución. Pero en este caso prefiero ser preciso ya que hay más métodos sobrecargados ... – sl3dg3

Cuestiones relacionadas