如何获得财产反思DisplayAttribute? [英] How to get DisplayAttribute of a property by Reflection?
本文介绍了如何获得财产反思DisplayAttribute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个助手这样的方法,让我的属性名(试图避免魔术字符串)
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屋!
查看全文