void MyMethod(string something, params object[] parameters)
{
foreach (object parameter in parameters)
{
// Get the name of each passed parameter
}
}
例如,如果我按以下方式调用该方法,我想获取名称“myFirstParam”和“anotherParam”。
string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);
也许反射(reflection)就是答案?也许这是不可能的?我知道 this question 的存在,但该解决方案在这里不起作用。
(请不要回答“这不是一个好主意”。这不是我的问题。)
最佳答案
这完全不可能。
这里只是一些甚至没有意义的情况:
MyMethod("abc", new object[5]);
MyMethod("abc", "def");
MyMethod("abc", var1 + var2);
MyMethod("abc", SomeMethod());
MyMethod("abc", b ? a : c);
MyMethod("abc", new object());
MyMethod("abc", null);
事实上,局部变量名甚至没有被编译到程序集中。
关于c# - 获取传递给 C# 方法的参数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6025858/