Reflection - get attribute name and value on property

后端 未结 15 2064
谎友^
谎友^ 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:18

    private static Dictionary GetAuthors()
    {
        return typeof(Book).GetProperties()
            .SelectMany(prop => prop.GetCustomAttributes())
            .OfType()
            .ToDictionary(a => a.GetType().Name.Replace("Attribute", ""), a => a.Name);
    }
    

    Example using generics (target framework 4.5)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    
    private static Dictionary GetAttribute(
        Func valueFunc)
        where TAttribute : Attribute
    {
        return typeof(TType).GetProperties()
            .SelectMany(p => p.GetCustomAttributes())
            .OfType()
            .ToDictionary(a => a.GetType().Name.Replace("Attribute", ""), valueFunc);
    }
    

    Usage

    var dictionary = GetAttribute(a => a.Name);
    

提交回复
热议问题