.net 反射应用
反射Reflection:System.Reflection,是.Net Framework提供的一个帮助类库,可以从dll读取并使用metadata. 获取对象的方法名称,字段名称,属性名称:
C#是一种强类型语言,静态语言,编译时就确定好类型保证安全。dynamic编译器不检查,运行时才检查。反射的动态加载和动态创建对象 以及配置文件结合实现可扩展。
1demo:
Stopwatch watch = new Stopwatch();
watch.Start();
//Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");//1 动态加载
//Type dbHelperType = assembly.GetType("Ruanmou.DB.SqlServer.SqlServerHelper");//2 获取类型
for (int i = 0; i< 1000_000; i++)
{
Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");//1 动态加载
Type dbHelperType = assembly.GetType("Ruanmou.DB.SqlServer.SqlServerHelper");//2 获取类型
object oDBHelper = Activator.CreateInstance(dbHelperType);//3 创建对象
object oDBHelper = Activator.CreateInstance(dbHelperType,true);//3 创建对象 可以访问私有方法
IDBHelper dbHelper = (IDBHelper)oDBHelper;//4 接口强制转换
MethodInfo method=dbHelperType.GetMethod("show");
method.Invoke(oDBHelper,null);
dbHelper.Query();//5 方法调用
}
watch.Stop();
reflectionTime = watch.ElapsedMilliseconds;
简单工厂:
private static string IDBHelperConfig = ConfigurationManager.AppSettings["IDBHelperConfig"];
private static string DllName = IDBHelperConfig.Split(',')[1];
private static string TypeName = IDBHelperConfig.Split(',')[0];
public static IDBHelper CreateInstance()
{
Assembly assembly = Assembly.Load(DllName);
Type type = assembly.GetType(TypeName);
object oDBHelper = Activator.CreateInstance(type);
IDBHelper iDBHelper = oDBHelper as IDBHelper;
return iDBHelper;
}
2.几种加载的方法:
Assembly assembly = Assembly.Load("oa.DB.MySql");//1 动态加载 一个完整dll名称不需要后缀 从exe所在的路径进行查找
Assembly assembly1 = Assembly.LoadFile(@"D:oaMyReflectioninDebugoa.DB.MySql.dll");//完整路径
Assembly assembly2 = Assembly.LoadFrom("oa.DB.MySql.dll");//当前路径
Assembly assembly3 = Assembly.LoadFrom(@"oaMyReflectioninDebugoa.DB.MySql.dll");//当前路径
3.获取dll 对象的方法名称,字段名称,属性名称:
foreach (var type in assembly.GetTypes())
{
//type.IsGenericType
Console.WriteLine(type.Name);
foreach (var method in type.GetMethods())
{
Console.WriteLine(method.Name);
}
foreach (var method in type.GetFields())
{
Console.WriteLine(method.Name);
}
foreach (var method in type.CustomAttributes)
{
Console.WriteLine(method.ToString());
}
}