Reflection - get attribute name and value on property

后端 未结 15 1893
谎友^
谎友^ 2020-11-22 04:59

I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.

public class Book
{
    [Author(\"         


        
15条回答
  •  遥遥无期
    2020-11-22 05:19

    public static class PropertyInfoExtensions
    {
        public static TValue GetAttributValue(this PropertyInfo prop, Func value) where TAttribute : Attribute
        {
            var att = prop.GetCustomAttributes(
                typeof(TAttribute), true
                ).FirstOrDefault() as TAttribute;
            if (att != null)
            {
                return value(att);
            }
            return default(TValue);
        }
    }
    

    Usage:

     //get class properties with attribute [AuthorAttribute]
            var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                foreach (var prop in props)
                {
                   string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);
                }
    

    or:

     //get class properties with attribute [AuthorAttribute]
            var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
            IList values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();
    

提交回复
热议问题