📅  最后修改于: 2022-03-11 14:48:42.887000             🧑  作者: Mango
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
public static class AttributeHelper
{
public static TValue GetPropertyAttributeValue(
Expression> propertyExpression,
Func valueSelector)
where TAttribute : Attribute
{
var expression = (MemberExpression) propertyExpression.Body;
var propertyInfo = (PropertyInfo) expression.Member;
var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
return attr != null ? valueSelector(attr) : default(TValue);
}
}
//USAGE:
var author = AttributeHelper.GetPropertyAttributeValue(prop => prop.Name, attr => attr.Author);
// author = "AuthorName"