2011-12-01 19 views

cevap

-1

Sen statik yöntemle yapacağı gibi bu yöntemi erişmek için elinden:

var like = typeof(StringEx).GetMethod("Like", new[] { typeof(string), typeof(string) }); 
+0

Evet, ben statik yöntemi ( – CodeAddicted

+0

Ne istisna ilgili bir istisna var, böyle yapıyor ama ben? Kodu test ettiğimde, "like" değişkeni uygun şekilde başlatıldı. –

+0

Bu benim için işe yaramadı, "BindingFlags.Static" içermesi gerekiyordu. – Colin

1

Başka kullanmalıdır diğer uzatma yöntemleri almak için

Type extendedType = typeof(StringEx); 
MethodInfo myMethodInfo = extendedType.GetMethod("Like", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic , null, new[] {typeof(string), typeof(string)},null); 
5

kullanın bu uzantı yöntemi:: aşırı yük bindingAttr parametresi ile getMethod

public static class ReflectionExtensions 
{ 
    public static IEnumerable<MethodInfo> GetExtensionMethods(this Type type, Assembly extensionsAssembly) 
    { 
     var query = from t in extensionsAssembly.GetTypes() 
        where !t.IsGenericType && !t.IsNested 
        from m in t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) 
        where m.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false) 
        where m.GetParameters()[0].ParameterType == type 
        select m; 

     return query; 
    } 

    public static MethodInfo GetExtensionMethod(this Type type, Assembly extensionsAssembly, string name) 
    { 
     return type.GetExtensionMethods(extensionsAssembly).FirstOrDefault(m => m.Name == name); 
    } 

    public static MethodInfo GetExtensionMethod(this Type type, Assembly extensionsAssembly, string name, Type[] types) 
    { 
     var methods = (from m in type.GetExtensionMethods(extensionsAssembly) 
         where m.Name == name 
         && m.GetParameters().Count() == types.Length + 1 // + 1 because extension method parameter (this) 
         select m).ToList(); 

     if (!methods.Any()) 
     { 
      return default(MethodInfo); 
     } 

     if (methods.Count() == 1) 
     { 
      return methods.First(); 
     } 

     foreach (var methodInfo in methods) 
     { 
      var parameters = methodInfo.GetParameters(); 

      bool found = true; 
      for (byte b = 0; b < types.Length; b++) 
      { 
       found = true; 
       if (parameters[b].GetType() != types[b]) 
       { 
        found = false; 
       } 
      } 

      if (found) 
      { 
       return methodInfo; 
      } 
     } 

     return default(MethodInfo); 
    } 
} 

böyle kullanın:

var assembly = Assembly.GetExecutingAssembly(); //change this to whatever assembly the extension method is in 

var methodInfo = typeof(string).GetExtensionMethod(assembly,"Like",new[] { typeof(string)}); 
İlgili konular