如何通过反射获取属性的 DisplayAttribute? [英] How to get DisplayAttribute of a property by Reflection?

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

问题描述

我有一个像这样的 Helper 方法来获取 PropertyName(试图避免使用魔法字符串)

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

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

但是有时我的 PropertyNames 的命名也不好.所以我宁愿使用 DisplayAttribute.

However sometimes my PropertyNames aren't named well either. So I would like to rather use the DisplayAttribute.

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

请注意,我使用的是 Silverlight 4.0.我找不到常用的命名空间 DisplayAttributeName 属性.

Please be aware I am using Silverlight 4.0. I couldnt find the usual namespace DisplayAttributeName attribute for this.

如何更改我的方法以读取 eproperty 的属性(如果可用)?

How can I change my method to read the attribute (if available) of th eproperty instead?

非常感谢,

推荐答案

这应该有效:

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

这篇关于如何通过反射获取属性的 DisplayAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆