1、什么是反射
反射是.NET中的重要机制,通过反射,可以在程序运行时获得程序集中的所有类型(包括接口、类,结构等),并且还可以直接创建对象,使用对象的方法。总之,用一句话总结就是:反射可以获得程序或程序集的信息,也可以动态的加载程序集,并创建其中某个类型的实例,执行实例中的方法。
2、反射用到的命名空间、类
首先,使用反射,需要引用.Net FrameWork 中的一个命名空间,System.Reflection
然后会用到这个程序集中的一个类:Assembly,使用这个类主要是为了将我们即将使用的程序集加载到当前程序中。
还会用到一个类:Type,这个类位于System命名空间下,使用这个类主要是为了存储动态加载程序集中的类型。然后如果要创建示例对象的话,还需要使用System命名空间下的类Activator
3、代码示例
public class Common
{
private static string appSpaceName = ConfigurationManager.AppSettings["appSpaceName"];
private static string appClassName = ConfigurationManager.AppSettings["appClassname"];
/// <summary>
/// Use interface to translate the obtained type,so you can use the class method directly
/// </summary>
public void TestReflection()
{
Assembly assembly = Assembly.Load(appSpaceName);
Type type = assembly.GetType(appClassName);
Object obj = Activator.CreateInstance(type);
IBaseDataAccess iBaseDataAccess = (IBaseDataAccess)obj;
iBaseDataAccess.Query();
}
public void TestReflectionExe()
{
Assembly assembly = Assembly.Load(appSpaceName);
Type type = assembly.GetType(appClassName);
Object obj = Activator.CreateInstance(type);
MethodInfo methodInfo = type.GetMethod("Query");
if (methodInfo != null)
{
methodInfo.Invoke(obj, null);
}
}
}