2012-07-19 9 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

IsGenericMethodをチェックし、GetMethodsを使用し、GetMethodを使用しないでください。ボーナスとして

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

関連する問題