反射

个人理解反射应该就是根据类型创建对象,然后调用一些方法。使用反射时可以不引用命名空间

主要为以下三步
Assembly assembly = Assembly.Load("DB.Sqlserver");//反射的入口,根据类库的名称,动态加载dll
主要为以下两步,因为类型的获取也可以通过实例化;
eg:People people = new People();Type type = assembly.GetType(people);//type = typeof(people);
Type type = assembly.GetType("DB.Sqlserver.ReflectionTest");//基于类的完整名称 找出类型
object oObject = Activator.CreateInstance(type);//根据类型,创建对象

可用于以下几种情况:

1 依赖接口,完成可配置可扩展

2 去掉接口,反射调用方法,包括私有方法

3. 反射破坏单例

4 反射获取属性和赋值

5 封装数据库访问层

代码如下:

//通过反射获取信息、创建对象、调用方法,并通过其dll,pdf文件是可配置扩展

            Console.WriteLine("*******************反射第一节*******************");
            IDBHelper iDBHelper = new DBHelper();
            iDBHelper.Query();
            string nameSpace = ConfigurationManager.AppSettings["DB.Interface.IDBHelper"];
            string[] nameSpaceArray = nameSpace.Split(',');

            //Assembly assembly = Assembly.Load("DB.Sqlserver");//反射的入口,加载dll文件
            Assembly assembly = Assembly.Load(nameSpaceArray[0]);
            Console.WriteLine("*********************GetModules*********************");
            foreach (Module module in assembly.GetModules())
            {
                Console.WriteLine("名称:{0}", module.FullyQualifiedName);
            }
            Console.WriteLine("*********************GetType*********************");
            foreach (Type type in assembly.GetTypes())
            {
                Console.WriteLine("名称:{0}", type.FullName);
            }
            Console.WriteLine("*********************创建对象*********************");
            //Type dbHelperType = assembly.GetType("DB.Sqlserver.DBHelper");/基于类的完整名称 找出类型
            Type dbHelperType = assembly.GetType(nameSpaceArray[1]);//基于类的完整名称 找出类型
            object oDBHelper = Activator.CreateInstance(dbHelperType);//创建对象 
            IDBHelper dbHelperReflection = (IDBHelper)oDBHelper;//可用is 然后as 进行判断
            dbHelperReflection.Query();
            //(oDBHelper is IDBHelper) as IDBHelper; 错误写法
            Console.WriteLine("请在键盘上按下任意一个键,然后开始执行下一步。");
            Console.ReadKey();
View Code

//方法的调用与单例的破坏
            Assembly assembly = Assembly.Load("DB.Sqlserver");//反射的入口,动态加载dll
            Type type = assembly.GetType("DB.Sqlserver.ReflectionTest");//基于类的完整名称 找出类型
            object oObject = Activator.CreateInstance(type);//根据类型,创建对象
            Console.WriteLine("*********************GetMethods*********************");
            foreach (MethodInfo method in type.GetMethods())
            {
                Console.WriteLine("名称:{0}", method.Name);
            }
            MethodInfo show_1 = type.GetMethod("Show1");//无参调用
            show_1.Invoke(oObject, null);
            MethodInfo show_2 = type.GetMethod("Show2");//含参调用
            show_2.Invoke(oObject, new object[] { 1 });
            Console.WriteLine("*********************重载方法的调用*********************");
            MethodInfo show3_1 = type.GetMethod("Show3", new Type[] { });//无参
            show3_1.Invoke(oObject, null);

            MethodInfo show3_2 = type.GetMethod("Show3", new Type[] { typeof(int) });//int
            show3_2.Invoke(oObject, new object[] { 32 });

            MethodInfo show3_3 = type.GetMethod("Show3", new Type[] { typeof(string) });//字符串
            show3_3.Invoke(oObject, new object[] { "3_3" });
            Console.WriteLine("*********************私有方法的调用*********************");
            MethodInfo show_4 = type.GetMethod("Show4", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            show_4.Invoke(oObject, new object[] { "黑科技之私有方法的调用" });

            Type typeSingle = assembly.GetType("DB.Sqlserver.Singleton");
            object oObjectSingle = Activator.CreateInstance(typeSingle, true);
            Console.ReadKey();
View Code
//获取属性和赋值
            Console.Writeln("*****Common*****"); 
            People people = new People();
            people.Id = 11;
            people.Name = "笨鸟";
            Console.WriteLine("People.Id={0},People.Name={1}", people.Id, people.Name);
            //用反射实现
            Type type = typeof(People);// people.GetType().FullName; 找到类型
            Object oObject = Activator.CreateInstance(type);//创建对象
            foreach (var prop in type.GetProperties())
            {
                if (prop.Name.Equals("Id"))
                {
                    prop.SetValue(oObject, 12);
                }
                if (prop.Name.Equals("Name"))
                {
                    prop.SetValue(oObject, "信天游");
                }
                Console.WriteLine("属性名称为{0},值是{1}", prop.Name, prop.GetValue(oObject));
            }
            DBHelper dbHelper = new DBHelper();
            User user = dbHelper.QueryDomain<User>();
            Console.ReadKey();
            #endregion
View Code
//数据库层的封装,通过实体类与数据库的表对应,这里的T对应的则是一个User实体类
private static string ConnectionStringCustomers = ConfigurationManager.ConnectionStrings["SqlconnString"].ConnectionString;
 public T QueryDomain<T>()
        {
            int id =1;
            Type type = typeof(T);
            T t = (T)Activator.CreateInstance(type);
            //[],中括号的作用是预防关键字
            string columns = string.Join(",",type.GetProperties().Select(p=>string.Format("[{0}]",p.Name)));
            string sql = string.Format("Select {0} from [{1}] where Id = {2}",columns,type.Name,id);
            using (SqlConnection conn = new SqlConnection(ConnectionStringCustomers))
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                if(reader.Read())
                {
                    foreach(var prop in type.GetProperties())
                    {
                        string propertyName = prop.Name;
                        prop.SetValue(t, reader[propertyName]);
                        Console.WriteLine("属性名称为{0},值是{1}", prop.Name, prop.GetValue(t));
                    }
                }
            }
            return t;
        }
View Code

 

 

posted @ 2017-02-26 21:08  _Nestling  阅读(238)  评论(0编辑  收藏  举报