mercredi 19 décembre 2018

How to get custom attribute of a property within a property in a class

My task is to the set/initialize all the properties tagged with custom attributes inside a class, derived to the class & properties within properties of that class. Example:

 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;
        }
    }

In this method, I also want to get custom attributes properties for property "ClassB" along with properties from Class A, D & E. How to achieve that?

    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
    }





Aucun commentaire:

Enregistrer un commentaire