获取参数的旧名称 [英] Get a parameter's old name

查看:49
本文介绍了获取参数的旧名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在追踪时,我认为做类似的事情会很有帮助

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

我希望将"myVariable"分配给oldName. GetOldName应该做什么?

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

有人问过类似的事情:

获取变量或参数的名称

但是在所有这些情况下,都会将"aVariable"分配给oldName.

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

更新:旧名称是在将参数/变量发送到函数之前调用的名称.我在这里使用它作为变量只是为了便于解释. 这样做的原因是调试.当我的程序收到错误时,我想知道变量的值是多少.我目前必须发送Log(错误变量名变量值).当您编写这些Debug语句中的1000条时,您会想到可以简化的方式.我要问的是可以简化问题.

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?

推荐答案

此信息需要由调用方捕获并提供.在C#6中,可以使用nameof运算符轻松实现它,尽管您需要在调用者代码中应用它:

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

并将Log方法定义为:

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.

这篇关于获取参数的旧名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆