10 feb 2012

example of working with custom attributes on properties in c#

using System.Reflection;
public sealed class MyAttribute : Attribute
    {
        private bool _MYbool = true;

        public bool MYbool
        {
            get { return __MYbool; }
            set { __MYbool= value; }
        }
        public MyAttribute()
        {
        }
        public MyAttribute(Boolean value)
        {
            _MYbool = value;
        }
    }





/// This Routine checks that the CalculationAttribute is Set or not
/// Put this function in a public static Class
/// 
/// the name of the object
/// the propertyname where to check on
/// 
public static Boolean PropertyCheckTo(this object SourceObj, string PropertyName)
 {
   PropertyInfo[] SourceProps = SourceObj.GetType().GetProperties();
   foreach (PropertyInfo pi in SourceProps)
   {
     if (pi.Name == PropertyName)
       {
       MyAttribute att = (MyAttribute )Attribute.GetCustomAttribute(pi, typeof(MyAttribute ));
         if (att != null)
         {
            return true;
         }
        }                
    }
    return false;
  }

Geen opmerkingen:

Een reactie posten