2012-07-19 47 views
17

假設存在如下所述的類X,如何獲取非泛型方法的方法信息?下面的代碼會拋出異常。如何在.NET中使用GetMethod區分通用簽名和非通用簽名?

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"); 
    } 
} 

回答

24

不要使用GetMethod,使用GetMethods,然後檢查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"); 
    } 
} 

作爲獎勵 - 擴展方法:

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); 
    } 
} 

然後,只需:

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

我很驚訝,這不是默認.NET的一部分。 – marsze 2016-04-13 13:26:51