📌  相关文章
📜  属性 C# 反射变量更新站点:stackoverflow.com - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:42.887000             🧑  作者: Mango

代码示例10
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"