簡體   English   中英

如何通過Reflection獲取屬性的DisplayAttribute?

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

我有一個像這樣的Helper方法來獲取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屬性。

如何更改我的方法來讀取eproperty的屬性(如果可用)?

非常感謝,

這應該工作:

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