Attributes are classes that allow you to add additional information to elements of your class structure(types, methods, properties, and so forth).This sample demonstrates the creation and use of custom attributes to extend and modify the behavior of code,Below is the code.
Attributes class:
Next step I defined three classes with my custom attributes.
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