【问题标题】:How to get DisplayAttribute of a property by Reflection?如何通过反射获取属性的 DisplayAttribute?
【发布时间】:2023-03-28 22:56:01
【问题描述】:

我有一个像这样的 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 的属性(如果可用)?

非常感谢,

【问题讨论】:

    标签: c# .net silverlight reflection


    【解决方案1】:

    这应该有效:

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

    【讨论】:

    • 如果您使用资源文件,您将需要使用GetName() 方法,而不仅仅是Name 属性,即最后一行将返回((DisplayAttribute)displayAttributes[0]).GetName();
    • 这里可能不需要对 displayAttributes != null 进行空检查,因为 GetCustomAttributes 总是返回一个对象[]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2010-11-02
    • 2014-08-27
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多