2011-12-01 50 views
5

我有一个扩展方法:如何使用GetMethod静态扩展方法

public static class StringEx 
{ 
    public static bool Like(this string a, string b) 
    { 
     return a.ToLower().Contains(b.ToLower()); 
    } 
} 

如何正确通过GetMethod与我的参数反映呢?我已经试过这没有成功(有大约静态方法除外):

var like = typeof(StringEx).GetMethod("Like", new[] {typeof(string), typeof(string)}); 
comparer = Expression.Call(prop, like, value); 

回答

-1

你可以访问此方法,你会与任何静态方法来实现:

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

是的,我做这样的,但我已经得到了有关静态方法( – CodeAddicted

+0

什么异常的异常?当我测试代码时,'like'变量被正确初始化。 –

+0

这不适合我,我需要包括“BindingFlags.Static”。 – Colin

1

您应该使用其他的超载GetMethod与BindingAttr参数:

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

使用这个扩展的方法来获得其他扩展方法:

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

使用方法如下:

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

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