Fengzhimei@Dot.Net
Designing My Colorful Dream
posts - 77,  comments - 196,  trackbacks - 3
    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
posted on 2004-06-25 01:29 fengzhimei 阅读(1402) 评论(3) 编辑 收藏

FeedBack:
2004-06-25 09:25 | unruledboy(灵感之源)
simple yet effective
 回复 引用   
2004-06-25 09:26 | unruledboy(灵感之源)
simple yet effective
 回复 引用   
2004-06-25 15:22 | 番茄鸡蛋面
good! learn a new point of .net. Thanks.

 回复 引用   
These postings are provided "AS IS" with no warranties, and confer no rights.
Translate this page to chinese
Locations of visitors to this page
昵称:fengzhimei
园龄:7年9个月
粉丝:0
关注:0

<2004年6月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

搜索

 
 

常用链接

随笔分类

随笔档案

.Text Skin

Blog I Read

Cool Tools

Exchange Bloggers

Game

Javascript

My Friend

Others

Regular Expression

SharePoint Bloggers

SOA

Sqlserver

积分与排名

  • 积分 - 135197
  • 排名 - 723

最新评论

阅读排行榜

评论排行榜

推荐排行榜