c# - 如何通过反射获取属性的 DisplayAttribute?

标签 c# .net silverlight 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 属性。

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

非常感谢,

最佳答案

这应该有效:

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

关于c# - 如何通过反射获取属性的 DisplayAttribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5499459/

相关文章:

c# - 加载表单时禁用按钮并在关闭表单时启用按钮

javascript - Web 推送通知 'UnauthorizedRegistration' 或 'Gone' 或 'Unauthorized' - 订阅到期

winforms - 在 Silverlight for Windows Phone 7 中打开新表单

c# - Amazon S3 PutObject 非常慢

c# - 学习 .NET 3.5 的资源

c# - 提交试用版WP7应用

Silverlight XAML 错误

c# - 获取 ASP.NET MVC 中的角色列表

c# - 在 C# 中对包含子项的列表进行排序

.net - Remove(),Clear()或Dispose()