反射的作用:在程序运行时,加载dll,从而得到其中的一些信息,如type,property,等。同时还可以对其赋值,或调用其中的某些方法。
命名空间及类型
C#中,关于反射要用的的所有程序集都在命名空间System.Reflection中,下面简单列举和介绍一些其中常用的程序集:
Assembly 用于加载程序集,并且可以获得该程序集的大部分信息,如版本信息,区域信息等
其初始化方法有:
Assembly assembly=Assembly.Load();
Assembly assembly=Assembly.LoadFrom();
Assembly assembly=Assembly.LoadFile();
其中:
LoadFile 方法用来来加载和检查具有相同标识但位于不同路径中的程序集。但不会加载程序的依赖项。- Type 用于获取实例
获取实例的三种方法:
1.使用object.GetType(); 如:
Student st = new Student(); var type = st.GetType();
2.System.Type.GetType()静态方法,该方法有重载版,后面有两个bool的参数,用于指定当前类型不能找到是是否抛出异常,和是否区分大小写()
Type t = Type.GetType("Student",false,true);
3.使用typeofType t = typeof(Student);
3.常用类
(1) EventInfo 事件的信息(2) FieldInfo 字段的信息
(3) MethodInfo 方法的信息
(4) ParameterInfo 参数的信息
(5) PropertyInfo 属性的信息
(6) MemberInfo 是抽象基类,为 EventInfo、FieldInfo 、MethodInfo、PropertyInfo等类型定义了公共的行为。
- Type 用于获取实例
这里就不一一详细介绍了,下面贴出自己的代码
using System;
using System.Collection.Generic;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Assembly ass;
Type type;
Object obj;
Object any = new Object();
ass = Assembly.LoadFile("E:\\ClassLibrary1.dll");
type = ass.GetType("ReflectionTest.WriteTest");
MethodInfo method = type.GetMethod("WriteString");
string test = "test";
int i = 1;
Object[] parametors = new Object[] {test, i};
obj = ass.CreateInstance("ReflectionTest.WriteTest");
method.Invoke(obj, parametors);//函数调用
PropertyInfo property = obj.GetType().GetProperty("ints");
int k = 6;
var tempStr = k.ToString();
property.SetValue(obj, string.IsNullOrEmpty(tempStr) ? null : Convent.ChangeType(tempStr, property.PropertyType), null);//类型转换
}
}
}