Get a parameter's old name

2019-09-26 02:26发布

When I am tracing, I think it would be useful to do something like

//In the main function
{
  Log(myVariable);
}

Which sends the variable to a generic function like this

//In the Logger file
public static void TraceMessage<T>(T aVariable)
{
   string oldName=GetOldName(aVariable);
}

I want "myVariable" to be assigned to oldName. What should GetOldName do?

Something similar was asked here:

get name of a variable or parameter

But in all of those cases, "aVariable" is assigned to oldName.

Update: Old name is what the parameter/variable was called before it was sent to the function. I use it as a variable here just for ease of explaining. The reason for this is debugging. When my program receives an error I would like to know what the value of my variables are. I currently have to send Log(the error, the variable name, the variable value). When you write 1000 of the these Debug statements you think of ways this could be simplified. What I am asking would simplify the problem.

Why did my question get downvoted and how can I improve the question?

1条回答
Anthone
2楼-- · 2019-09-26 02:59

This information needs to be captured and provided by the caller. In C# 6, it can be easily achieved using the nameof operator, although you'll need to apply this in your caller code:

Log(myVariable, nameof(myVariable));

Edit: If you only want to specify your variable once, you can use:

Log(() => myVariable);

And define your Log method as:

public static void Log<T>(Expression<Func<T>> expression)
{
    string oldName = ((MemberExpression)expression.Body).Member.Name;
    object value = expression.Compile().Invoke();
}

However, this will be much slower than the alternative, and is not guaranteed behaviour.

查看更多
登录 后发表回答