2011-12-01 3 views

답변

-1

당신은 당신이 정적 방법으로 할 것이 메소드에 액세스 할 수 :

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

예, 나는 정적 메소드 ( – CodeAddicted

+0

어떤 예외에 대한 예외를 가지고, 그런 일을하지만 무엇입니까? 코드를 테스트 할 때'like' 변수가 제대로 초기화되었습니다. –

+0

이것은 나를 위해 작동하지 않았다, 나는 "BindingFlags.Static"을 포함 할 필요가 있었다. – Colin

1

당신은 다른를 사용한다 다른 확장 방법을 얻을 수

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

사용이 확장 방법 : 의 과부하는 BindingAttr 매개 변수로을 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); 
    } 
} 

이처럼 사용

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

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