Determine the name of the variable used as a param

2019-07-15 09:36发布

How would you, in C#, determine the name of the variable that was used in calling a method?

Example:

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(myVar);
}

public void MyMethod2(string parm)
{
  // do some reflection magic here that detects that this method was called using a variable called 'myVar'
}

I understand that the parameter might not always be a variable, but the place I am using it is in some validation code where I am hoping that the dev can either explicitly state the friendly name of the value they are validating, and if they don't then it just infers it from the name of the var that they called the method with...

4条回答
Root(大扎)
2楼-- · 2019-07-15 10:00

Variables are meant to be convenient identifiers that assign semantic meaning to entities. Programmatically them in the way you're describing seems like a pretty big code smell. Besides, if it's really that important to know, couldn't you just pass in a second parameter?


Edit: The OP updated his question to include this line:

I understand that the parameter might not always be a variable, but the place I am using it is in some validation code where I am hoping that the dev can either explicitly state the friendly name of the value they are validating, and if they don't then it just infers it from the name of the var that they called the method with...

If they explicitly state it and that's important to you, it should definitely be passed in as a parameter to the function.

查看更多
再贱就再见
3楼-- · 2019-07-15 10:02

There is a way, but it's pretty ugly.

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(() => myVar);
}

public void MyMethod2(Expression<Func<string>> func)
{
  var localVariable = (func.Body as MemberExpression).Member.Name;
  // localVariable == "myVar"
}

As you can see, all your calls would have to be wrapped into lambdas and this method breaks down if you start to do anything else in the lambda besides return a single variable.

查看更多
叛逆
4楼-- · 2019-07-15 10:14

Unfortunately, that's going to be very hard, if not impossible.

Why exactly do you need the name of the variable originally sent in?

Remember that there might not be an actual variable used:

MyMethod2(myVar + "! 123");

In this case, myVar holds just parts of the value, the rest is calculated in the expression at runtime.

查看更多
在下西门庆
5楼-- · 2019-07-15 10:14

It sounds to me like you should be using an Enum as an identifier for your variable, rather than trying to determine the name of your variable. The whole point of a variable is that it's just a human readable name to represent a bit of memory.

You could do:

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(myVar, VariableType.MyVar);
}

public void MyMethod2(string parm, VariableType type)
{
  if (type == VariableType.MyVar)
  {
  }
}
查看更多
登录 后发表回答