How can I get the name of a C# static class property using reflection?

后端 未结 5 1343
孤街浪徒
孤街浪徒 2020-12-11 22:41

I want to make a C# Dictionary in which the key is the string name of a static property in a class and the value is the value of the property. Given a static property in th

5条回答
  •  时光取名叫无心
    2020-12-11 22:51

    If all you want is just to be able to refer to a single, specific property in one place in the code without having to refer to it by a literal string, then you can use an expression tree. For example, the following code declares a method that turns such an expression tree into a PropertyInfo object:

    public static PropertyInfo GetProperty(Expression> expr)
    {
        var member = expr.Body as MemberExpression;
        if (member == null)
            throw new InvalidOperationException("Expression is not a member access expression.");
        var property = member.Member as PropertyInfo;
        if (property == null)
            throw new InvalidOperationException("Member in expression is not a property.");
        return property;
    }
    

    Now you can do something like this:

    public void AddJavaScriptToken(Expression> propertyExpression)
    {
        var p = GetProperty(propertyExpression);
        _javaScriptTokens.Add(p.Name, (string) p.GetValue(null, null));
    }
    
    public void RegisterJavaScriptTokens()
    {
        AddJavaScriptToken(() => Tokens.TOKEN_ONE);
        AddJavaScriptToken(() => Tokens.TOKEN_TWO);
    }
    

提交回复
热议问题