现在的位置: 首页 > 综合 > 正文

反射

2018年02月18日 ⁄ 综合 ⁄ 共 2977字 ⁄ 字号 评论关闭

程序包含模块,而模块包含类型,类型又包含成员。

反射则提供了封装程序集、模块和类型的对象。您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。

首先认识反射中常用到的一些类Type、Assembly、Activator、MemberInfo、PropertyInfo  :

Type类 表示类型声明:类类型、接口类型、数组类型、值类型、枚举类型、类型参数、泛型类型定义,以及开放或封闭构造的泛型类型。

 可以通过以下两种方式获得Type:
               
1.通过类获得Type: Type t=typeof(Person);

                2.通过对象获得Type:Person p=new Person(); Type t=p.GetType();   

Type类 常用方法

        bool IsAssignableFrom(Type c):判断当前的类型的变量是不是可以接受c类型变量的赋值。
           Type type = assembly.GetType("MyAssembly.Person");
           Type studentType = assembly.GetType("MyAssembly.Student");	
           Console.WriteLine(type.IsAssignableFrom(studentType));
           Result:True      因为Person p=new Student();

       

        bool IsInstanceOfType(object o):判断对象o是否是当前类的实例(当前类可以是o的类、父类、接口)   
        Person p = new Student();      //判断p是否是一个Student类的实例
        bool r = typeof(Student).IsInstanceOfType(p);//True
     	bool IsSubclassOf(Type c)://判断当前类是否是类c的子类。实用于类,不适用于接口
	bool r = typeof(Student).IsSubclassOf(typeof(Person));//判断Student是否是Person的子类
        bool r = typeof(Person).IsAbstract;//判断Person是否是抽象类或接口

Assembly类表示一个程序集,它是一个可重用、无版本冲突并且可自我描述的公共语言运行时应用程序构造块。
Assembly.LoadFile(string) 加载指定路径上的程序集文件的内容。
        Assembly.GetExportedTypes()获取此程序集中定义的公共类型,这些公共类型在程序集外可见。
        Assembly.GetTypes() 获取此程序集中定义的类型。
Assembly.GetType() 获取当前实例的 Type。 (继承自 Object。)
        Assembly.GetType(name)获取程序集实例中具有指定名称的 Type 对象。如: Type type = assembly.GetType("MyAssembly.Person");


Activator类包含特定的方法,用以在本地或从远程创建对象类型,或获取对现有远程对象的引用.
Activator.CreateInstance(Type, Object[])  使用与指定参数匹配程度最高的构造函数创建指定类型的实例
MemberInfo类  抽象类,有很多子类,下面讲的类都继承自它,获取程序集成员的相关信息(类型、方法、事件、字段和属性)


PropertyInfo类  
    主要成员:CanRead、CanWrite、PropertyType属性类型;SetValue、GetValue:读取值,设置值,第一个参数是实例对象,因为set、get要针对具体实例,最后一个参数null。pInfo.SetValue(p1, 30, null)


简单运用:

	static void Main(string[] args)
        {
            //通过反射动态调用另一个程序集中的方法
            //1加载程序集
            string path = AppDomain.CurrentDomain.BaseDirectory;//获取当前.exe执行文件的路径
            path = Path.Combine(path, "MyAssembly.dll");//拼接程序集的路径
            Assembly assembly = Assembly.LoadFile(path);
            //2创建Person类的对象
            Type type = assembly.GetType("MyAssembly.Person");
            object o = Activator.CreateInstance(type,"wolf",22,"未知");//实例化
            //3获取方法的类型
             MethodInfo methodInfo = type.GetMethod("SayHi");
            //4反射调用方法
             methodInfo.Invoke(o, null);
            Console.Read();
        }

经典类型转换:

   
        protected BaseVo ConvertDto2Vo(object dto, Type voType)
        {
            if (dto != null)
            {
                PropertyInfo[] pros = voType.GetProperties();
                BaseVo rtnEntity = (BaseVo)Activator.CreateInstance(voType);
                PropertyInfo[] array = pros;
                int i = 0;
                while (i < array.Length)
                {
                    PropertyInfo pro = array[i];
                    try
                    {
                        PropertyInfo paraPro = dto.GetType().GetProperty(pro.Name);
                        if (paraPro != null)
                        {
                            pro.SetValue(rtnEntity, paraPro.GetValue(dto, null), null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    i++;
                    continue;
                }
                return rtnEntity;
            }
            else
            {
                return null;
            }
        }
        protected object ConvertVo2Dto(BaseVo vo, Type dtoType)
        {
            if (vo != null)
            {
                PropertyInfo[] pros = dtoType.GetProperties();
                object rtnDto = Activator.CreateInstance(dtoType);
                PropertyInfo[] array = pros;
                int i = 0;
                while (i < array.Length)
                {
                    PropertyInfo pro = array[i];
                    try
                    {
                        PropertyInfo paraPro = vo.GetType().GetProperty(pro.Name);
                        if (paraPro != null)
                        {
                            pro.SetValue(rtnDto, paraPro.GetValue(vo, null), null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    i++;
                    continue;
                }
                return rtnDto;
            }
            else
            {
                return null; 
            }
        }

参考文章:http://www.cnblogs.com/wolf-sun/

抱歉!评论已关闭.