.Net反射

序言

通过代码实现反编译

反射存在的意义

反射是什么呢?反射是动态获取程序集的元数据(metadata)的一种技术。反射是.NetFramework类库提供的帮助类,动态加载dll实现程序的可配置可扩展。

个人认为反射最突出的优点或存在的合理性:在不修改程序原码的情况下,实现程序功能的动态调整(Runtime动态对象创建)

反射实际用途

智能提示

反射最重要的用途就是开发各种通用框架。

插件开发

System.Reflection
Assembly a = Assembly.LoadFile(dirStr);
Type t = a.GetType(classStr)
object obj = Activator.CreateInstance(type,new object[] { "沐风" });//使用具有一个参数的构造函数创建一个实例 相当于New

反射与泛型结合 深拷贝

 public M ObjectDeepCopy<M>(M inM)
        {
            Type t = inM.GetType();
            M outM = (M)Activator.CreateInstance(t);
            foreach (PropertyInfo p in t.GetProperties())
            {
                t.GetProperty(p.Name).SetValue(outM, p.GetValue(inM));
            }
            return outM;
        }
反射

DataTable转换成数据实体集

 public static List<T> TableToEntity<T>(DataTable table) where T : class
        {
            if (table == null || table.Rows.Count == 0)
            {
                return null;
            }

            var propertys = typeof(T).GetProperties().Where(p => table.Columns.Contains(p.Name)).ToList();

            var list = new List<T>(table.Rows.Count);

            table.AsEnumerable().ToList().ForEach(r =>
            {
                var model = Activator.CreateInstance<T>();

                propertys.ForEach(p =>
                {
                    if (r[p.Name] is DBNull)
                    {
                        return;
                    }

                    p.SetValue(model, ChangeType(r[p.Name], p.PropertyType), null);
                });

                list.Add(model);
            });

            return list;
        }
DataTable转换成数据实体集

ORM框架-结合SqlSugar

资料

https://www.cnblogs.com/Stephenchao/p/4481995.html

https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html

net反射详解

.NET中使用反射实现简易插件机制

posted @ 2019-01-29 10:26  ~沐风  阅读(206)  评论(0编辑  收藏  举报