This is a mirror of official site: http://jasper-net.blogspot.com/

Iterate Over Object Properties and Property Attributes w/Reflection

| Wednesday, March 9, 2011
Define custom attribute class as follows as well as placing the attribute reference on the property “FirstName”.  In the following we are creating our own custom attribute by defining an attribute class which derives from Attribute which makes identifying attribute definitions in metadata easy.  The AttributeUsage attribute can be used to limit which asset the attribute can be placed such as class, struct, property etc.  In addition, in the example below 
I have disallowed multiple similar attributes from being used on the same property designated by AllowMultiple = false
 
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class CustomItemAttribute : Attribute {

        public string FieldName { get; set; }

        private bool _isMultiValue = false;
        public bool IsMultiValue {
            get { return _isMultiValue; }
            set {
                _isMultiValue = value;
            }
        }

        public CustomItemAttribute(string fieldName) {
            this.FieldName = fieldName;        
        }
    }

   public class Item{
[CustomItem("myfieldname")]
        public string FirstName { get; set;}

   }

Now to iterate over the properties. Notice in the class Item above how we can exclude the 'Attribute' text in the name of the attribute applied to the FirstName property. Below we can use Type.GetProperties method to get the names of the properties for a specific type. The method GetProperties returns an array of PropertyInfo objects and the property names aer available through PropertyInfo.Name. If you want to get only a subset of the properties such as public static ones you can use BindingFlags parameters (Public/NonPublic, Instance/Static). i.e. PropertyInfo[] infos = typeof(Item).GetProperties(BindingFlags.Public|BindingFlags.Static);
        private void IterateOverProperties() {
            CustomItemAttribute customItemAttribute;
            Type type = typeof(Item);
   //for each property of object of Item
            foreach (PropertyInfo propInfo in type.GetProperties()) {
                //for each custom attribute on the property loop
                foreach CustomItemAttribute attr in propInfo.GetCustomAttributes(typeof(CustomItemAttribute), false)) {
                    customItemAttribute = attr as CustomItemAttribute;

Posted via email from Jasper-net

0 comments: