1
我正在構建一個方法來從System.ComponentModel.DataAnnotations中獲取DisplayAttribute以顯示屬性的標籤。建立一個使用lambda表達式的方法調用
[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") + ":";
我可以使用泛型使用一個更優雅的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);
的問題是我怎麼能做到這一點?
是的!謝謝! – iuristona