如何使用反射获取变量名? [英] How to get variable name using reflection?

查看:17
本文介绍了如何使用反射获取变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

static void Main()
{
    var someVar = 3;

    Console.Write(GetVariableName(someVar));
}

这个程序的输出应该是:

The output of this program should be:

someVar

如何使用反射来实现这一点?

How can I achieve that using reflection?

推荐答案

使用反射无法做到这一点,因为一旦编译到 IL,变量就没有名称.但是,您可以使用表达式树并将变量提升为闭包:

It is not possible to do this with reflection, because variables won't have a name once compiled to IL. However, you can use expression trees and promote the variable to a closure:

static string GetVariableName<T>(Expression<Func<T>> expr)
{
    var body = (MemberExpression)expr.Body;

    return body.Member.Name;
}

您可以按如下方式使用此方法:

You can use this method as follows:

static void Main()
{
    var someVar = 3;

    Console.Write(GetVariableName(() => someVar));
}

请注意,这非常慢,所以不要在应用程序的性能关键路径中使用它.每次运行这段代码时,都会创建几个对象(这会导致 GC 压力),并在其掩护下调用许多不可内联的方法并使用一些重反射.

Note that this is pretty slow, so don't use it in performance critical paths of your application. Every time this code runs, several objects are created (which causes GC pressure) and under the cover many non-inlinable methods are called and some heavy reflection is used.

有关更完整的示例,请参阅此处.

For a more complete example, see here.

更新

在 C# 6.0 中,nameof 关键字被添加到语言中,这允许我们执行以下操作:

With C# 6.0, the nameof keyword is added to the language, which allows us to do the following:

static void Main()
{
    var someVar = 3;

    Console.Write(nameof(someVar));
}

这显然更方便,并且成本与将字符串定义为常量字符串文字相同.

This is obviously much more convenient and has the same cost has defining the string as constant string literal.

这篇关于如何使用反射获取变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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