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

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

问题描述

例如,

static void Main()
{
    var someVar = 3;

    Console.Write(GetVariableName(someVar));
}

该程序的输出应该是:

someVar

我怎样才能做到这一点使用反射?

How can I achieve that using reflection?

推荐答案

这是不可能用反射来做到这一点,因为变量将不会有一次编译IL的名称。但是,您可以使用前pression树木和促进变量封闭:

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

请注意,这是pretty慢,所以不要在你的应用程序的性能关键路径使用它。这code运行时,都会创建多个对象(这会导致GC pressure)和掩护下,许多非可以内联方法被调用,使用一些沉重的反思。

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.

有关更完整的示例,请参见 href=\"https://cuttingedge.it/blogs/steven/pivot/entry.php?id=37\">。

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天全站免登陆