Friday, August 29, 2008

Attribute Based Programming

//>> Custom Attribute
AttributeUsage(
AttributeTarget.Class
Field
Method
Property
Constructor
Event
)]
public class SkillAttribute : System.Attribute
{
public Skill level;
public SkillAttribute(SkillLevel s)
{
_level = s;
}
}
public enum SkillLevel
{
Guru,
Senior,
Junior,
Praciticer
}

// >>Usage
[Student(SkillLevel.Practicer)]
public class Student
{
[Skill(SkillLevel.Guru)]
public void Add(string name)
{
// ...
}
}

// >> Inspecting
public class SomeClass
{
public void DoReflection()
{
object[] attribs = typeof(Student).GetCustomAttributes(false);
if (attribs.length > 0 && attribs[0] is SkillAttribute)
{
// ...
}
MethodInfo minfo = typeof(Student).GetMethod("Add");
minfo.GetCustomAttributes(false);
}
}

No comments: