2012-07-19 26 views
17

Giả sử tồn tại một lớp X như được mô tả bên dưới, làm cách nào để lấy thông tin phương pháp cho phương pháp không chung chung? Mã dưới đây sẽ ném một ngoại lệ.Làm cách nào để phân biệt giữa các chữ ký chung và không chung bằng GetMethod trong .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"); 
    } 
} 

Trả lời

24

Không sử dụng GetMethod, sử dụng GetMethods, sau đó kiểm tra 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"); 
    } 
} 

Như một phần thưởng - một phương pháp khuyến nông:

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

Sau đó chỉ cần:

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

Tôi ngạc nhiên đây không phải là một phần của NET theo mặc định. – marsze

Các vấn đề liên quan