2016-06-02 7 views
3

다음 코드를 고려 (문자열 이름을 [] 유형 입력) 메서드를 호출합니다. 그러한 Foo 메서드가 없으면 프로그램에서 단계를 건너 뛸 필요가 있습니다. 이를 수행하는 방법은 다음과 같습니다.예기치 않은 동작이

public static MethodInfo GetFooMethodIfExists(Type parameterType) 
{ 
    return typeof(FooHelpers).GetMethod("Foo", new Type[] { parameterType }); 
} 

합리적인 해결책처럼 보이겠습니까? Type.GetMethod(string name, Type[] types)에 대한 설명서에 따르면

이제
// Returns: 
//  A System.Reflection.MethodInfo object representing the public method whose 
//  parameters match the specified argument types, if found; otherwise, null. 

은, 이제 다음을 시도하자 대신 null을 반환하는, 그것은 int 매개 변수 방법을 반환

MethodInfo m = GetFooMethodIfExists(typeof(short)); 

. 방금 Type.GetMethod(string name, Type[] types)의 출력에 의존하여 문서 상태로 동작하는 반사 작업이 많은 프로젝트를 마쳤습니다. 문제가 많이 발생했습니다.

아무도 왜 이런 일이 발생했는지 및/또는 다른 방법을 설명 할 수 있습니까?

답변

4

BindingFlags.ExactBinding으로 문제를 해결할 수 있습니다. 기본적으로 매개 변수 유형에 대해 반사를 엄격하게 적용합니다. 다음은이 플래그를 사용하도록 메소드를 수정하는 방법입니다.

public static MethodInfo GetFooMethodIfExists(Type parameterType) 
{ 
    return typeof (FooHelpers).GetMethod(
     "Foo", 
     BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding, 
     (Binder) null, 
     new[] {parameterType}, 
     (ParameterModifier[]) null); 
} 
+0

감사합니다. –