自定义属性信息

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#程序设计》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值