Reflection - get attribute name and value on property

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

    If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the CustomAttributeData API:

    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Reflection;
    
    public static class Program
    {
        static void Main()
        {
            PropertyInfo prop = typeof(Foo).GetProperty("Bar");
            var vals = GetPropertyAttributes(prop);
            // has: DisplayName = "abc", Browsable = false
        }
        public static Dictionary GetPropertyAttributes(PropertyInfo property)
        {
            Dictionary attribs = new Dictionary();
            // look for attributes that takes one constructor argument
            foreach (CustomAttributeData attribData in property.GetCustomAttributesData()) 
            {
    
                if(attribData.ConstructorArguments.Count == 1)
                {
                    string typeName = attribData.Constructor.DeclaringType.Name;
                    if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
                    attribs[typeName] = attribData.ConstructorArguments[0].Value;
                }
    
            }
            return attribs;
        }
    }
    
    class Foo
    {
        [DisplayName("abc")]
        [Browsable(false)]
        public string Bar { get; set; }
    }
    

提交回复
热议问题