获取传递给方法的参数名称[复制]

时间:2022-08-02 21:03:03

This question already has an answer here:

这个问题在这里已有答案:

Duplicate: Determine the name of the variable used as a parameter to a method

重复:确定用作方法参数的变量的名称

Is there any way to retrieve the name of a parameter that was passed into a method e.g.

有没有办法检索传递给方法的参数的名称,例如

int someParameter = 1;
Method(someParameter);

public void Method(int parameter)
{
    // I want the name of 'parameter' which will be 'someParameter'.
}

3 个解决方案

#1


No. It's only the value which is passed in as the argument. All the method gets is the integer. The fact that the expression happened to be just evaluating a variable is unknown as far as your method is concerned.

不,它只是作为参数传递的值。所有方法得到的都是整数。就您的方法而言,表达式恰好只是评估变量的事实是未知的。

#2


No, there is no way.

不,没有办法。

This will be followed by a bunch of people showing weird lambda expression ways to change the call site and kinda get the name, but the short answer is no.

接下来是一群人显示奇怪的lambda表达方式来改变呼叫站点并获得名称,但简短的回答是否定的。

#3


The only way perhaps will be with annotations with run-time retention. But then, it will be the name of the annotation, not of the parameter itself. A parameter name is just a syntactic artifact of the language. It does not get carried over to the compiled result.

唯一的方法可能是带有运行时保留的注释。但是,它将是注释的名称,而不是参数本身的名称。参数名称只是该语言的语法工件。它不会被转移到编译结果。

#1


No. It's only the value which is passed in as the argument. All the method gets is the integer. The fact that the expression happened to be just evaluating a variable is unknown as far as your method is concerned.

不,它只是作为参数传递的值。所有方法得到的都是整数。就您的方法而言,表达式恰好只是评估变量的事实是未知的。

#2


No, there is no way.

不,没有办法。

This will be followed by a bunch of people showing weird lambda expression ways to change the call site and kinda get the name, but the short answer is no.

接下来是一群人显示奇怪的lambda表达方式来改变呼叫站点并获得名称,但简短的回答是否定的。

#3


The only way perhaps will be with annotations with run-time retention. But then, it will be the name of the annotation, not of the parameter itself. A parameter name is just a syntactic artifact of the language. It does not get carried over to the compiled result.

唯一的方法可能是带有运行时保留的注释。但是,它将是注释的名称,而不是参数本身的名称。参数名称只是该语言的语法工件。它不会被转移到编译结果。