2011-10-15 6 views
1

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

이 메소드의 호출이 될 수 있습니다

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

lblNome.Text = GetDisplay(typeof(Person), "FirstName") + ":"; 

내가 좋아하는, 제네릭을 사용하여 더 우아한 sintax을 사용할 수 있습니다

전화 :

GetDisplay<Person>("FirstName"); 

그래서,이 같은 전화를 돌려 람다 표현식을 사용하여보다 더 우아하고 싶습니다 :

GetDisplay<Person>(p => p.FirstName); 

문제는 내가 이것을 달성 할 수있는 방법인가?

string GetDisplay<T>(Expression<Func<T, object>> expression) 
{ 
    return GetDisplay<T>(expression.PropertyName()); 
} 

답변

2

내가 람다 식에 의해 주어진 속성 이름을 가져 오기 위해 사용하는 방법입니다! 고맙습니다!
+0

예 : 당신은 단지 이전 방법을 호출 할 수 있습니다이 방법을 사용

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

: 여기 – iuristona

관련 문제