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;
        }

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

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

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


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

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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();
        }

猜你喜欢

转载自blog.csdn.net/weixin_42339460/article/details/80704631