How to get variable name using reflection?

This question already has an answer here:

  • Finding the variable name passed to a function 16 answers

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

    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.

    UPDATE

    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.


    You can't, using reflection. GetVariableName is passed the number 3, not a variable. You could do this via code inspect of the IL, but that's probably in the too-hard basket.

    链接地址: http://www.djcxy.com/p/69026.html

    上一篇: Android异构gridview像pinterest?

    下一篇: 如何使用反射获取变量名称?