zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Get names of the params passed to a C# method

c# to The of get method params names
2023-09-11 14:14:18 时间

Get names of the params passed to a C# method


void MyMethod(string something, params object[] parameters) { foreach (object parameter in parameters) { // Get the name of each passed parameter } }

For example, if I call the method in the following way, I want to get the names "myFirstParam" and "anotherParam".

string myFirstParam = "some kind of text";
string anotherParam = 42;
MyMethod("test", myFirstParam, anotherParam);

Perhaps reflection is the answer? Perhaps it's just not possible? I am aware of the existance of this question, but that solution won't work here.

(Please do not respond with "This is not a good idea". That is not my question.)

 

回答:

This is totally impossible.

Here are just a few cases where it doesn't even make sense:

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

In fact, local variable names aren't even compiled into the assembly.