如果我有一个方法如:
public void MyMethod(int arg1, string arg2)
我如何获得参数的实际名称? 我似乎无法在MethodInfo中找到任何实际上会给我参数名称的内容。
我想写一个看起来像这样的方法:
public static string GetParamName(MethodInfo method, int index)
所以,如果我用以下方法调用此方法:
string name = GetParamName(MyMethod, 0)
它将返回“arg1”。这可能吗?
答案 0 :(得分:58)
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;
}
以上样本应该做你需要的。
答案 1 :(得分:4)
尝试这样的事情:
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;
}
答案 2 :(得分:3)
nameof(arg1)
将返回变量arg1
答案 3 :(得分:1)
没有任何错误检查:
public static string GetParameterName ( Delegate method , int index )
{
return method.Method.GetParameters ( ) [ index ].Name ;
}
您可以使用'Func< TResult>'和衍生品,使其适用于大多数情况