Attributes class:
[AttributeUsage(AttributeTargets.Class)] public class Person : Attribute { private string m_FirstName; private string m_LastName; public string FirstName { get { return m_FirstName; } set { this.m_FirstName = value; } } public string LastName { get { return m_LastName; } set { this.m_LastName = value; } } public Person(string strFirstName, string strLastName) { this.m_FirstName = strFirstName; this.m_LastName = strLastName; } }A custom attributes class must with AttributeUsage attribute, AttributeUsage indicates the class is a user-defined attribute class.
Next step I defined three classes with my custom attributes.
[Person("san", "zhang") ] public class FirstClass { /*...*/ } [Person("si", "li") ] public class SecondClass { /*...*/ } [Person("wu", "wang") ] public class ThirdClass { /*...*/ }Now I get the user-defined attributes by using Reflection:
public class GetCustomAttributes { public static void Main(string[] args) { PersonInformation(typeof(FirstClass)); PersonInformation(typeof(SecondClass)); PersonInformation(typeof(ThirdClass)); } public static void PersonInformation(Type t) { Attribute[] attrs = Attribute.GetCustomAttributes(t); foreach(Attribute attr in attrs) { if (attr is Person) { Person person = (Person)attr; Console.WriteLine("FirstName:{0} LastName:{1}", person.FirstName, person.LastName); } } Console.WriteLine(); } }That's all about it
