Reflection - get attribute name and value on property

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

    Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttributes() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.

    Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):

    public static Dictionary GetAuthors()
    {
        Dictionary _dict = new Dictionary();
    
        PropertyInfo[] props = typeof(Book).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                AuthorAttribute authAttr = attr as AuthorAttribute;
                if (authAttr != null)
                {
                    string propName = prop.Name;
                    string auth = authAttr.Name;
    
                    _dict.Add(propName, auth);
                }
            }
        }
    
        return _dict;
    }
    

提交回复
热议问题