C# 特性AttributeUsage简介与使用教程

  using System;

  using System.Linq;

  namespace AttributeUsagePractice

  {

  [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]

  public class HelpAttribute : Attribute

  {

  public HelpAttribute(){}

  public HelpAttribute(String Description_in)

  {

  this.description = Description_in;

  }

  protected String description;

  public String Description

  {

  get { return this.description; }

  }

  }

  [Help("this is a HelpAttribute use class")]

  public class UseHelpAttribute

  {

  }

  public class UseHelpAttributeDerive : UseHelpAttribute

  {

  }

  class Program

  {

  public static void Main(string[] args)

  {

  // TODO: Implement Functionality Here

  UseHelpAttributeDerive objHelpAttribute = new UseHelpAttributeDerive();

  Type t = objHelpAttribute.GetType();

  object [] objAttrs = t.GetCustomAttributes(typeof(HelpAttribute),true);

  if(objAttrs!= null && objAttrs.Length > 0)

  {

  object temp = objAttrs.First();

  HelpAttribute myAttr = temp as HelpAttribute;

  Console.WriteLine("类描述:{0}", myAttr.Description);

  }

  else

  {

  Console.WriteLine("没有类描述");

  }

  Console.ReadKey(true);

  }

  }

  }