C# Attribute 特性 的用处举例

**特性(Attribute)是用来 向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。所以要获取某个类的特性,需要通过反射实现。**

1、自定义一个 CheckCodeAttribute


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

    public class CheckCodeAttribute : System.Attribute
    {

        public string UserName = "";
        public string CheckTime = "";
        public int Score = 0;




        public CheckCodeAttribute(string name,string time,int score)
        {
            UserName = name;
            CheckTime = time;
            Score = score;
        }


        /// <summary>
        /// 计算分数的方法
        /// </summary>
        /// <returns></returns>
        public double GetScore()
        {
            return Score * 0.8;
        }

    }

2、将上面的自定义Attribute应用于 一个类上

    [CheckCode("张伟", "2017-03-22",99)]
    public class DoWork
    {


         public string GetData()
         {
             return DateTime.Now.ToString("yyyy-MM-dd");
         }

    }

3、通过反射 来获取 DoWork 类相关的 Attribute 信息

 static void Main(string[] args)
        {


            System.Reflection.MemberInfo info = typeof(DoWork);
            //object[] attributes = info.GetCustomAttributes(true);

            CheckCodeAttribute att = (CheckCodeAttribute)Attribute.GetCustomAttribute(info, typeof(CheckCodeAttribute));

            double score = att.GetScore();

            System.Console.WriteLine(att.UserName + " 于 " + att.CheckTime + " 检查了代码,得分:" + score);

            Console.ReadKey();
        }
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值