簡體   English   中英

如何獲取方法參數的名稱?

[英]How can you get the names of method parameters?

如果我有一個方法,例如:

public void MyMethod(int arg1, string arg2)

我將如何獲取參數的實際名稱? 我似乎無法在 MethodInfo 中找到任何實際上會給我參數名稱的內容。

我想寫一個看起來像這樣的方法:

public static string GetParamName(MethodInfo method, int index)

因此,如果我使用以下命令調用此方法:

string name = GetParamName(MyMethod, 0)

它會返回“arg1”。 這可能嗎?

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

沒有任何錯誤檢查:

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

您可以使用 'Func<TResult>' 和導數來使其適用於大多數情況

nameof(arg1)將返回變量arg1的名稱

https://msdn.microsoft.com/en-us/library/dn986596.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM