加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:18:21 所属栏目:百科 来源:网络整理
导读:我有一个这样的帮助方法来获取PropertyName(试图避免魔术字符串) public static string GetPropertyNameT(ExpressionFuncT expression) { var body = (MemberExpression) expression.Body; return body.Member.Name; } 不过有时候,我的PropertyNames也没有命
我有一个这样的帮助方法来获取PropertyName(试图避免魔术字符串)
public static string GetPropertyName<T>(Expression<Func<T>> expression)
        {
            var body = (MemberExpression) expression.Body;
            return body.Member.Name;
        }

不过有时候,我的PropertyNames也没有命名.所以我宁愿使用DisplayAttribute.

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

请注意我正在使用Silverlight 4.0.我找不到这个通常的命名空间DisplayAttributeName属性.

如何更改我的方法来读取属性(如果可用的话)呢?

非常感谢,

解决方法

这应该工作:
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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读