简体   繁体   English

如何通过Reflection获取属性的DisplayAttribute?

[英]How to get DisplayAttribute of a property by Reflection?

I have a Helper method like this to get me the PropertyName (trying to avoid magic strings) 我有一个像这样的Helper方法来获取PropertyName(试图避免魔术字符串)

public static string GetPropertyName<T>(Expression<Func<T>> expression)
        {
            var body = (MemberExpression) expression.Body;
            return body.Member.Name;
        }

However sometimes my PropertyNames aren't named well either. 但有时我的PropertyNames也没有好好命名。 So I would like to rather use the DisplayAttribute. 所以我想宁愿使用DisplayAttribute。

[Display(Name = "Last Name")]
public string Lastname {get; set;}

Please be aware I am using Silverlight 4.0. 请注意我使用的是Silverlight 4.0。 I couldnt find the usual namespace DisplayAttributeName attribute for this. 我无法找到通常的命名空间DisplayAttributeName属性。

How can I change my method to read the attribute (if available) of th eproperty instead? 如何更改我的方法来读取eproperty的属性(如果可用)?

Many Thanks, 非常感谢,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM