如何在类的属性中获取属性的自定义属性

时间:2018-12-19 18:06:25

标签: c# .net inheritance reflection attributes

我的任务是设置/初始化在类中标记有自定义属性的所有属性,这些属性派生到类和该类的属性内的属性。 示例:

 class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.InjectableProperties();
        }
    }


    public class A : C
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameA{ get; set; }

        public B ObjB { get; set; }

        public IEnumerable<PropertyInfo> InjectableProperties()
        {
            var response = new List<PropertyInfo>();
            // get the mnodule properties
            var moduleProperties = GetType().GetProperties();
         foreach (var moduleProperty in moduleProperties)
            {
                var attribute = moduleProperty.GetCustomAttributes(typeof(CodeModulePropertyAttribute), false)
                    .FirstOrDefault();

                if (attribute != null && ((CodeModulePropertyAttribute)attribute).PropertyType ==
                    ModulePropertyType.Injectable)
                {
                    response.Add(moduleProperty);
                }
            }

            return response // Only gives A,D &C . I also want custom attributes children properties within objB;
        }
    }

在这种方法中,我还想获取属性“ ClassB”的自定义属性属性以及A,D和E类的属性。如何实现?

    public class B
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameB { get; set; }
    }
    public class C : D
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameC { get; set; }
    }

    public class D
    {
        [CodeModuleProperty(ModulePropertyType.Injectable)]
        public string NameD { get; set; }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class CodeModulePropertyAttribute : Attribute
    {
        public CodeModulePropertyAttribute(ModulePropertyType propertyType)
        {
            PropertyType = propertyType;
        }

        public ModulePropertyType PropertyType { get; set; }


    }

    public enum ModulePropertyType
    {
        Injectable = 1,
        DynamicConfiguration = 2
    }

1 个答案:

答案 0 :(得分:0)

对于财产

object attr = typeof(MyClass)
              .GetProperty("NameB")
              .GetCustomAttributes(typeof(CodeModuleProperty), false)
              .FirstOrDefault();

对于班级

object attr = typeof(MyClass)
              .GetCustomAttributes(typeof(CodeModuleProperty), false)
              .FirstOrDefault();

如果要检查所有属性,只需执行.GetProperties并用for-each对其进行迭代,然后调用GetCustomAttributes