我正在构建一个方法来从System.ComponentModel.DataAnnotations获取DisplayAttribute以在属性的标签上显示。
[Display(Name="First Name")]
public string FirstName { get; set; }
该方法运作良好:
string GetDisplay(Type dataType, string property)
{
PropertyInfo propInfo = dataType.GetProperty(property);
DisplayAttribute attr = propInfo.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault();
return (attr == null) ? propInfo.Name : attr.Name;
}
方法的调用可以是:
lblNome.Text = GetDisplay(typeof(Person), "FirstName") + ":";
我可以使用Generics使用更优雅的sintax,例如:
string GetDisplay<T>(string property)
{
PropertyInfo propInfo = typeof(T).GetProperty(property);
DisplayAttribute attr = propInfo.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault();
return (attr == null) ? propInfo.Name : attr.Name;
}
电话:
GetDisplay<Person>("FirstName");
所以,我想使用lambda表达式更加优雅地调用这样的调用:
GetDisplay<Person>(p => p.FirstName);
问题是如何实现这一目标?
答案 0 :(得分:2)
这是我用来获取lambda表达式给出的属性名的方法:
public static string PropertyName<T1, T2>(this Expression<Func<T1, T2>> expression)
{
MemberExpression member = null;
if (expression.Body is MemberExpression)
member = expression.Body as MemberExpression;
if (expression.Body is UnaryExpression && expression.Body.NodeType == ExpressionType.Convert)
member = ((UnaryExpression)expression.Body).Operand as MemberExpression;
if (member == null)
throw new ArgumentException("Selector must point to a property or field.", "expression");
return member.Member.Name;
}
使用此方法,您只需调用上一个方法:
string GetDisplay<T>(Expression<Func<T, object>> expression)
{
return GetDisplay<T>(expression.PropertyName());
}