2008-10-17 81 views
26

如果我有這樣的方法:如何獲取方法參數的名稱?

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

上面的示例應該做你所需要的。

3

嘗試是這樣的:

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

,沒有任何形式的錯誤檢查:

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

你可以使用 'Func鍵<TResult>' 和衍生品,使這項工作在大多數情況下

+3

沒有錯誤檢查只是要求麻煩。 – 2008-12-04 21:19:40