2008-10-17 3 views
26

I는 다음과 같은 방법이있는 경우 :메소드 매개 변수의 이름은 어떻게 얻을 수 있습니까?

public void MyMethod(int arg1, string arg2) 

가 어떻게 인수의 실제 이름을 얻기에 관하여 갈 것입니까? 실제로 매개 변수의 이름을 알려줄 MethodInfo에서 아무것도 찾을 수없는 것 같습니다.

나는이처럼 보이는 방법을 쓰고 싶습니다 : 나는이 메소드를 호출 그렇다면

public static string GetParamName(MethodInfo method, int index) 

을 :

string name = GetParamName(MyMethod, 0) 

그것은 "ARG1"를 반환합니다. 이것이 가능한가?

답변

50
public static string GetParamName(System.Reflection.MethodInfo method, int index) 
{ 
    string retVal = string.Empty; 

    if (method != null && method.GetParameters().Length > index) 
     retVal = method.GetParameters()[index].Name; 


    return retVal; 
} 

위의 샘플은 필요한 것을 수행해야합니다. 오류 검사의 어떤 종류없이

foreach(ParameterInfo pParameter in pMethod.GetParameters()) 
{ 
    //Position of parameter in method 
    pParameter.Position; 

    //Name of parameter type 
    pParameter.ParameterType.Name; 

    //Name of parameter 
    pParameter.Name; 
} 
3

이런 식으로 뭔가를 시도

public static string GetParameterName (Delegate method , int index) 
{ 
    return method.Method.GetParameters () [ index ].Name ; 
} 

당신은 대부분의 경우

을 위해이 작품을 만들기 위해 'Func을 <TResult>'및 파생 상품을 사용할 수 있습니다
1

:

+3

오류 검사는 문제가되지 않습니다. –

+3

@TomAnderson - 맹목적으로 인터넷에서 코드를 복사하는 중 문제가 발생했습니다. –

관련 문제