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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/214086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:25:01  来源:igfitidea点击:

How can you get the names of method parameters?

c#.netreflection

提问by Luke Foust

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". Is this possible?

它会返回“arg1”。这可能吗?

采纳答案by Tom Anderson

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.

上面的示例应该可以满足您的需求。

回答by Jeremy

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

回答by k?e?m?p? ?

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>' 和导数来使其适用于大多数情况

回答by Warren Parad

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