自定义属性信息

来源:互联网 发布:淘宝便宜的零食店 编辑:程序博客网 时间:2024/05/22 17:19

namespace Programming_CShar
{
 using System;
 using System.Reflection;

 //声明属性
 //第一个参数是一组表示目标的标志
 //第二个参数表示元数是否可以接受一个以上的该属性信息
 [AttributeUsage(AttributeTargets.Class |
   AttributeTargets.Constructor |
   AttributeTargets.Field |
   AttributeTargets.Method |
   AttributeTargets.Property,
   AllowMultiple=true)]
 public class BugFixAttribute : System.Attribute 
 {
  //属性信息有两种参数:位置型和命名型参数
  //位置型参数将传入构造函数,且必须以构造方法中声明的顺序传入;
  //命名型参数则以性质形式实现
  //[BugFixAttribute(107,"Jesse Liberty","03/04/05",Comment="Fixed off by one errors")]
  //上面的Comment为命名型参数,其余的为位置型
  public BugFixAttribute(int bugID,string programmer,string date)
  {
   this.bugID=bugID;
   this.programmer=programmer;
   this.date=date;
  }
  public int BugID
  {
   get
   {
    return bugID;
   }
  }
  public string Comment
  {
   get
   {
    return comment;
   }
   set
   {
    comment=value;
   }
  }
  public string Date
  {
   get
   {
    return date;
   }
   set
   {
    date=value;
   }
  }
  public string Programmer
  {
   get
   {
    return programmer;
   }
   set
   {
    programmer=value;
   }
  }
  private int bugID;
  private string comment;
  private string date;
  private string programmer;
 }

 [BugFixAttribute(121,"Jesse Liberty","04/05/06")]
 [BugFixAttribute(107,"Jesse Liberty","03/04/05",Comment="Fixed off by one errors")]
 public class MyMath
 {
  public double DoFunc1(double param1)
  {
   return param1 + DoFunc2(param1);
  }
  public double DoFunc2(double param1)
  {
   return param1 / 3;
  }
 }
 public class Tester
 {
  public static void Main()
  {
   MyMath mm=new MyMath();
   Console.WriteLine("Calling DoFunc1(7). Result:{0}",mm.DoFunc1(7));

   System.Reflection.MemberInfo inf=typeof(MyMath);
   object[] attributes;
   attributes=inf.GetCustomAttributes(typeof(BugFixAttribute),true);
   foreach(Object attribute in attributes)
   {
    BugFixAttribute bfa=(BugFixAttribute)attribute;
    Console.WriteLine("/nBugID:{0}",bfa.BugID);
    Console.WriteLine("Programmer:{0}",bfa.Programmer);
    Console.WriteLine("Date:{0}",bfa.Date);
    Console.WriteLine("Comment:{0}",bfa.Comment);
   }
   Console.ReadLine();
  }
 }
}
//代码来自《C#程序设计》

原创粉丝点击