[英]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
的名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.