1.反射是什么? 是微软提高的一个类包,访问dll里面的metadata,IL
2.为什么要用反射? 程序可配置和可以突破方法的权限限制
3.反射调用方法?反射创建对象? Assembly assembly = Assembly.LoadFrom("xxx.dll"); //dll名称(需要后缀) Type type = assembly.GetType("aaa.ReflectionTest"); object obj =Activator.CreateInstance(type) MethodInfo show =type.GetMethod("show1",new Type[]{"string",123}); show.Inoke(obj, new object[] { "11" });
4.通过反射操作类的属性,字段,方法?设置值和获取值 Type type = typeof(People); object oPeople =Activator.CreateInstance(type) foreach (FieldInfo field in type.GetFields()) //获取所有的字段 { if (field.Name.Equals("Description")) { field.SetValue(oPeople, "aaa"); } Console.WriteLine(field.Name); }
foreach (PropertyInfo prop in type.GetProperties()) { Console.WriteLine(prop.GetValue(oPeople)); } foreach (FieldInfo field in type.GetFields()) //获取所有的字段 { Console.WriteLine(field.GetValue(oPeople)); }
5.反射在框架中的应用,反射封装ORM的应用? public T Find<T>(int id) where T:class { Type type=Typeof(T); var pro=type.GetProperties().Select(p=>$"[{p.Name}]"); string pros=string.Join(",",pro); string sql=$"select {pros} from [{type.Name}] where id={id}"; string strConn=""; object oResult = Activator.CreateInstance(type); using (SqlConnection connection = new SqlConnection(strConn)) { using (SqlCommand command = new SqlCommand(sql, connection)) { connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { foreach (PropertyInfo prop in type.GetProperties()) { prop.SetValue(oResult, reader[prop.Name]); } } } } return (T)oResult; }
--------------------------
0.c#代码的执行过程: c#(编译器)-->dll/exe(metadata/IL)-->CLR/JIT-->机器码()01010101
1. appsettings.json配置文件配置要访问的类和dll "ReflictionConfig": "aaa.MySqlHelper,sss.dll"
2.代码读取dll,实例化一个配置类的对象 public static IDBHelper CreateInstance() { string ReflictionConfig = CustomConfigManager.GetConfig("ReflictionConfig"); string tyepName= ReflictionConfig.Split(",")[0]; string dllName = ReflictionConfig.Split(",")[1];
//Assembly assembly = Assembly.Load(dllName); //Dll名称,不需要后缀 Assembly assembly3 = Assembly.LoadFrom(dllName); //dll名称(需要后缀)
Type type = assembly3.GetType(tyepName); object obj = Activator.CreateInstance(type); return obj as IDBHelper; }
3. 反射可以突破方法的权限限制 100_000_000
4. 反射性能并不会消耗多大,100万次循环和普通方法相差3倍的时间,
单例模式=是一种常见类的写法, public class SingletonA { //私有成员,使用时分配内存 private static SingletonA _instance = null; //私有构造,杜绝直接new类 private SingletonA() { }
//获取实例 public static SingletonA GetInstance () {
if (_instance == null) { _instance = new SingletonA(); } return _instance; } }
-----------------------
Emit 是反射的一种; 懒加载=延迟加载执行; ORM表达式目录树; 实体生成器创建类=创建文件
|
请发表评论