简体   繁体   English

如何获取方法参数的名称?

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

If I have a method such as:如果我有一个方法,例如:

public void MyMethod(int arg1, string arg2)

How would I go about getting the actual names of the arguments?我将如何获取参数的实际名称? I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.我似乎无法在 MethodInfo 中找到任何实际上会给我参数名称的内容。

I would like to write a method which looks like this:我想写一个看起来像这样的方法:

public static string GetParamName(MethodInfo method, int index)

So if I called this method with:因此,如果我使用以下命令调用此方法:

string name = GetParamName(MyMethod, 0)

it would return "arg1".它会返回“arg1”。 Is this possible?这可能吗?

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

The above sample should do what you need.上面的示例应该可以满足您的需求。

Try something like this:尝试这样的事情:

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

without any kind of error checking:没有任何错误检查:

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

You could use 'Func<TResult>' and derivatives to make this work for most situations您可以使用 'Func<TResult>' 和导数来使其适用于大多数情况

nameof(arg1) will return the name of the variable arg1 nameof(arg1)将返回变量arg1的名称

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM