Use of attributes

    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:
     [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 regular_smile.gif

转载于:https://www.cnblogs.com/fengzhimei/archive/2004/06/25/18478.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值