How to get DisplayAttribute of a property by Reflection?

前端 未结 1 361
感情败类
感情败类 2020-12-18 23:13

I have a Helper method like this to get me the PropertyName (trying to avoid magic strings)

public static string GetPropertyName(Expression

        
相关标签:
1条回答
  • 2020-12-18 23:22

    This should work:

    public static string GetPropertyName<T>(Expression<Func<T>> expression)
    {
        MemberExpression propertyExpression = (MemberExpression)expression.Body;
        MemberInfo propertyMember = propertyExpression.Member;
    
        Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);
        if(displayAttributes != null && displayAttributes.Length == 1)
            return ((DisplayAttribute)displayAttributes[0]).Name;
    
        return propertyMember.Name;
    }
    
    0 讨论(0)
提交回复
热议问题