特性的使用,反射

1.自定义特性允许吧自定义元数据与元素关联起来。这些元数据是在编译过程中创建的,并嵌入到程序集中。反射是一个普通术语,他描述了了在运行过程中检查和处理程序元素的功能。

反射可以完成以下任务:

枚举类型的成员

实例化新对象

执行对象的成员

查找类型的信息

查找程序集的信息

检查应用于某种类型的自定义特性

创建和编译新的程序集

2.如何使用自定义特性和反射

编写自定义的特性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttributeTest
{
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    class NameAttribute:Attribute
    {
        public string name;  
        public NameAttribute(string name)
        {
            this.name = name;
        }
        public string MyName
        {
             get { return name; }
        }
    }
}
AttributeUsage特性是特性类的一个特征,用于标示自定义特性可以应用到哪些类型的程序元素上。
编写要使用自定义特性的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttributeTest
{
    //应用特性 NameAttribute
    [Name("lihua")]
    class Student
    {
       // public string firstName;
      
    }
}
[Name("lihua")]将NameAttribute应用到了Student类,student类就有了值为lihua的特性。通过反射可以获取这一值。

获取student的特性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyAttributeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //获取student类型
            Type defineType = typeof(Student);
         
            Console.WriteLine("__________________________");
            Console.WriteLine(defineType.Name);
            //获取自定义类型的所有特性
            Attribute[] attribs = Attribute.GetCustomAttributes(defineType);
            //显示student中特性赋予的所有值
            foreach (Attribute attrib in attribs)
           {
               //强制转化为NameAttribute
               NameAttribute natrb = attrib as NameAttribute;
               if (natrb == null)
               {
                   Console.WriteLine("NameAttribute does not exist");
               }
               else
               {
                   //获取自定义特性属性值
                   string myname = natrb.MyName;
                   Console.WriteLine(myname);
               }
           }
            Console.ReadLine();
        }
    }
}

使用:

例如编写一个软件更新信息的自定义特性,在有更新的类中添加此特性,赋予相关参数如更新日期和时间,就可以通过反射拿到类的该特性,展示更新信息。

 
posted @ 2014-12-01 15:56  lxdonge  阅读(180)  评论(0)    收藏  举报