2012-07-19 15 views
17

Suponiendo que exista una clase X como se describe a continuación, ¿cómo obtengo la información del método no genérico? El siguiente código arrojará una excepción.¿Cómo distingo entre firmas genéricas y no genéricas usando GetMethod en .NET?

using System; 

class Program { 
    static void Main(string[] args) { 
     var mi = Type.GetType("X").GetMethod("Y"); // Ambiguous match found. 
     Console.WriteLine(mi.ToString()); 
    } 
} 

class X { 
    public void Y() { 
     Console.WriteLine("I want this one"); 
    } 
    public void Y<T>() { 
     Console.WriteLine("Not this one"); 
    } 
} 

Respuesta

24

No utilice GetMethod, utilice GetMethods, a continuación, comprobar IsGenericMethod.

using System; 
using System.Linq; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var mi = Type.GetType("X").GetMethods().Where(method => method.Name == "Y"); 
     Console.WriteLine(mi.First().Name + " generic? " + mi.First().IsGenericMethod); 
     Console.WriteLine(mi.Last().Name + " generic? " + mi.Last().IsGenericMethod); 
    } 
} 

class X 
{ 
    public void Y() 
    { 
     Console.WriteLine("I want this one"); 
    } 
    public void Y<T>() 
    { 
     Console.WriteLine("Not this one"); 
    } 
} 

Como beneficio adicional - un método de extensión:

public static class TypeExtensions 
{ 
    public static MethodInfo GetMethod(this Type type, string name, bool generic) 
    { 
     if (type == null) 
     { 
      throw new ArgumentNullException("type"); 
     } 
     if (String.IsNullOrEmpty(name)) 
     { 
      throw new ArgumentNullException("name"); 
     } 
     return type.GetMethods() 
      .FirstOrDefault(method => method.Name == name & method.IsGenericMethod == generic); 
    } 
} 

A continuación, sólo:

static void Main(string[] args) 
{ 
    MethodInfo generic = Type.GetType("X").GetMethod("Y", true); 
    MethodInfo nonGeneric = Type.GetType("X").GetMethod("Y", false); 
} 
+0

Me sorprende que esto no es parte de .NET de forma predeterminada. – marsze

Cuestiones relacionadas